<?php

namespace App\Actions\Admin\Upload;

use App\Actions\Shared\BaseAction;
use App\Models\kelas;
use App\Models\siswa;
use App\Models\UploadSiswaKelas;
use App\Models\User;
use App\Traits\ApiResponseTrait;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Yajra\DataTables\DataTables;

class SiswaKelasAction extends BaseAction
{
    use ApiResponseTrait;

    public function __construct()
    {
        $this->modelClass = UploadSiswaKelas::class;
    }

    public function do_upload($request)
    {
        $request->validate([
            'files_siswa' => 'required|file|mimes:xlsx,xls,csv|max:2048',
            'kelas_id' => 'nullable|exists:kelas,id'
        ]);

        $kelas_id = $request->post('kelas_id');
        $kelas = Kelas::find($kelas_id);

        $folder = str_replace(' ', '_', strtolower($kelas->kode));

        $file = $request->file('files_siswa');
        $originalName = $file->getClientOriginalName();
        $storedName = time() . '.' . $file->getClientOriginalExtension();

        // $filePath = $file->storeAs('upload/siswa_kelas', $storedName, 'public');
        $location = 'upload/siswa_kelas/' . $folder;
        $filePath = $file->storeAs($location, $storedName, 'public');

        $uploaded = UploadSiswaKelas::create([
            'filename' => $storedName,
            'original_name' => $originalName,
            'file_type' => $file->getClientOriginalExtension(),
            // 'file_type' => $file->getClientMimeType(),
            'file_size' => $file->getSize(),
            'url' => Storage::url($filePath),
            'path' => $filePath,
            'status' => 'pending',
            'kelas_id' => $request->post('kelas_id'),
        ]);


        // $filePath = storage_path('app/public/upload/siswa_kelas/' . $storedName);
        $filePath = storage_path('app/public/' . $location . '/' . $storedName);
        // Load spreadsheet
        $spreadsheet = IOFactory::load($filePath);
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray(null, true, true, true); // key berdasarkan kolom: A, B, C...

        $header = array_shift($rows); // ambil header, abaikan kalau tidak perlu
        $rowCount = 0;
        $errors = [];

        foreach ($rows as $i => $row) {
            try {
                if (!empty($row['C']) && strtolower(trim($row['B'])) != 'nama') {
                    DB::transaction(function () use ($row, $kelas, $kelas_id, &$rowCount) {
                        $siswa = Siswa::create([
                            'nis'            => $row['E'],
                            'nisn'           => $row['C'],
                            'name'           => $row['B'],
                            'gender'         => $row['D'],
                            'tempat_lahir'   => $row['F'],
                            'tanggal_lahir'  => $row['G'],
                            'bidang_keahlian'=> $row['H'],
                            'program_keahlian'=> $row['I'],
                            'kompt_keahlian' => $row['J'],
                            'status_kelulusan' => $row['L'],
                            'kelas_id'       => $kelas_id,
                            'jurusan_id'     => $kelas->jurusan_id,
                            'kelas_name'     => $kelas->name,
                        ]);

                        User::create([
                            'email'           => $row['C'] . '@siswa.cc',
                            'username'        => $row['C'],
                            'password'        => bcrypt($row['C']),
                            'name'            => $row['B'],
                            'biodata_id'      => $siswa->id,
                            'primary_role_id' => 3,
                        ]);

                        $rowCount++;
                    });
                }
            } catch (\Exception $e) {
                $errors[] = [
                    'row' => $i + 2, // karena biasanya header di baris 1
                    'message' => $e->getMessage(),
                ];
            }
        }


        // Update pada instance yang sama
        $uploaded->update([
            'row_count' => $rowCount,
            'status' => empty($errors) ? 'completed' : 'error',
            'processing_completed_at' => now(),
            // 'errors' => $errors ?: null,
        ]);

        return $this->apiResponse($errors)
            ->message('Data pengguna berhasil ditemukan')
            ->send();
    }


    public function combokelas($request)
    {

        $data = kelas::select('id', 'name')
            ->where('is_active', true)
            ->get();

        $combo = $data->map(function ($item) {
            return [
                'id' => $item->id,
                'name' =>  ucwords($item->name),
                'kode' => $item->kode,
            ];
        });

        return $this->apiResponse($combo)
            ->message('Data pengguna berhasil ditemukan')
            ->send();
    }

    public function table()
    {
        $data = UploadSiswaKelas::select(['*', 'kelas.name'])
            ->join('kelas', 'upload_siswa_kelas.kelas_id', '=', 'kelas.id');
        return DataTables::of($data)
            ->addIndexColumn()
            ->addColumn('action', function ($row) {
                $btnMore = '';
                $btnview = '';
                // $btnview .= '<a class="btn btn-icon" href="javascript:void(0);" data-permision="user-update" onclick="onDeleteInduka(this)" data-params="' . base64_encode(json_encode($row)) . '">
                //                 <i class="ti ti-trash ti-md"></i>
                //             </a>';
                $btnview .= '<a class="btn btn-icon" href="javascript:void(0);" data-permision="user-update" onclick="onDownload(this)" data-params="' . base64_encode(json_encode($row)) . '">
                                <i class="ti ti-download ti-md"></i>
                            </a>';

                // $btnMore .= '<a class="dropdown-item" href="javascript:void(0);" data-permision="user-update" onclick="onEdit(this)" data-params="' . base64_encode(json_encode($row)) . '">Edit</a>';
                // $btnMore .= '<div class="dropdown-divider"></div>';
                $btnMore .= '<a class="dropdown-item" href="javascript:void(0);" data-permision="user-update" onclick="onDelete(this)" data-params="' . base64_encode(json_encode($row)) . '">Delete</a>';

                $btnDropdown = $btnMore === '' ? '' : '
                        <div class="dropdown">
                            <a href="javascript:;" class="btn dropdown-toggle hide-arrow btn-icon p-0" data-bs-toggle="dropdown" aria-expanded="false"><i class="ti ti-dots-vertical ti-md"></i></a>
                            <div class="dropdown-menu dropdown-menu-end">
                                ' . $btnMore . '
                            </div>
                        </div>
                ';

                return '
                    <div class="d-flex align-items-center">
                        ' . $btnview . '
                        ' . $btnDropdown . '
                    </div>
                    ';
            })
            ->rawColumns(['action'])
            ->make(true);
    }
}
