<?php

namespace App\Actions\Admin\Management;

use App\Actions\Shared\BaseAction;
use App\Models\jurusan;
use App\Models\Siswa;
use App\Traits\ApiResponseTrait;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Yajra\DataTables\DataTables;

class SiswaAction extends BaseAction
{
    use ApiResponseTrait;

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

    public function read($request)
    {
        $data = Siswa::find($request['id']);
        return $this->apiResponse($data)
            ->message('Data pengguna berhasil ditemukan')
            ->send();
    }

    public function validate(array $data, $tipe = 'store', $pk_id = null)
    {
        $rules = [
            'nis' => 'required|string|max:200',
            'name' => 'required|string|max:200',
            'jurusan_id' => 'required|string|max:200',
            'tempat_lahir' => 'required|string|max:200',
        ];

        if ($tipe === 'store') {
            $rules['nisn'] = 'required|string|max:25|unique:siswas,nisn';
        } else {
            $rules['nisn'] = 'required|string|max:25|unique:siswas,nisn,' . $pk_id;
        }

        $validator = Validator::make($data, $rules, $this->validateMessages()); // ✅ gunakan pesan custom

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

        return $validator->validated();
    }

    public function validateMessages()
    {
        return [
            'nisn.required'   => 'Kode Kompetensi wajib diisi.',
            'nisn.unique' => 'Kode Kompetensi sudah digunakan. Silakan gunakan kode lain.',
            'name.required'   => 'Nama Kompetensi wajib diisi.',
            'jurusan_id.required'   => 'Kompetensi wajib diisi.',
        ];
    }

    // Override fungsi create dengan validasi
    public function create(array $data)
    {
        $validated = $this->validate($data);
        $validated['nis'] = $data['nisn'];
        return parent::create($validated);
    }

    public function update(int $id, array $data)
    {
        $validated = $this->validate($data, 'update', $id);
        return parent::update($id, $validated);
    }

    public function combokompt($request)
    {

        $data = Jurusan::select('id', 'nama_jurusan', 'kode_jurusan')
            ->where('is_active', true)
            ->get();

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

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

    // Fungsi untuk mengambil data dengan DataTables
    public function table()
    {
        $data = Siswa::select(['siswas.id', 'siswas.nisn', 'siswas.name', 'siswas.gender', 'siswas.jurusan_id', 'jurusans.nama_jurusan AS nama_jurusan'])
            ->join('jurusans', 'siswas.jurusan_id', '=', 'jurusans.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>';

                $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>
                        ';
                // return '<a href="#" class="btn btn-sm btn-primary">Edit</a>';
            })
            ->rawColumns(['action'])
            ->make(true);
    }
}
