<?php

namespace App\Controllers\Admin;

use CodeIgniter\RESTful\ResourceController;
use App\Models\CertificateModel;

class CertificateController extends ResourceController
{
    protected $modelName = 'App\Models\CertificateModel';
    protected $format    = 'json';

    public function index()
    {
        $search = $this->request->getGet('search');
        $sort = $this->request->getGet('sort') ?? 'id';
        $order = $this->request->getGet('order') ?? 'DESC';

        $model = new CertificateModel();

        if ($search && strlen($search) >= 3) {
            $model->groupStart()
                ->like('title', $search)
                ->orLike('issuer', $search)
            ->groupEnd();
        } elseif ($search) {
            session()->setFlashdata('warning', 'Kata kunci pencarian minimal 3 karakter.');
        }

        $data = [
            'certificates' => $model->orderBy($sort, $order)->paginate(10),
            'pager' => $model->pager,
            'search' => $search,
            'sort' => $sort,
            'order' => $order,
            'title' => 'Daftar Sertifikat'
        ];

        return view('admin/certificate/index', $data);
    }

    public function new()
    {
        return view('admin/certificate/form', ['title' => 'Tambah Sertifikat']);
    }

    public function create()
    {
        $rules = [
            'title' => 'required|min_length[3]',
            'issuer' => 'required',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $data = [
            'title' => $this->request->getPost('title'),
            'issuer' => $this->request->getPost('issuer'),
            'issue_date' => $this->request->getPost('issue_date'),
            'credential_id' => $this->request->getPost('credential_id'),
            'credential_url' => $this->request->getPost('credential_url'),
            'description' => $this->request->getPost('description'),
        ];

        // Handle image upload
        $image = $this->request->getFile('image');
        if ($image && $image->isValid() && !$image->hasMoved()) {
            $imageName = $image->getRandomName();
            $image->move('uploads/certificates', $imageName);
            $data['image'] = 'uploads/certificates/' . $imageName;
        }
        
        $this->model->insert($data);
        return redirect()->to('/admin/certificate')->with('message', 'Sertifikat berhasil ditambahkan');
    }

    public function edit($id = null)
    {
        $data = [
            'certificate' => $this->model->find($id),
            'title' => 'Edit Sertifikat'
        ];
        return view('admin/certificate/form', $data);
    }

    public function update($id = null)
    {
        $rules = [
            'title' => 'required|min_length[3]',
            'issuer' => 'required',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $data = [
            'title' => $this->request->getPost('title'),
            'issuer' => $this->request->getPost('issuer'),
            'issue_date' => $this->request->getPost('issue_date'),
            'credential_id' => $this->request->getPost('credential_id'),
            'credential_url' => $this->request->getPost('credential_url'),
            'description' => $this->request->getPost('description'),
        ];

        // Handle image upload
        $image = $this->request->getFile('image');
        if ($image && $image->isValid() && !$image->hasMoved()) {
            $imageName = $image->getRandomName();
            $image->move('uploads/certificates', $imageName);
            $data['image'] = 'uploads/certificates/' . $imageName;
        }

        $this->model->update($id, $data);
        return redirect()->to('/admin/certificate')->with('message', 'Sertifikat berhasil diperbarui');
    }

    public function delete($id = null)
    {
        // Delete image file if exists
        $certificate = $this->model->find($id);
        if ($certificate && $certificate['image'] && file_exists($certificate['image'])) {
            unlink($certificate['image']);
        }
        
        $this->model->delete($id);
        return redirect()->to('/admin/certificate')->with('message', 'Sertifikat berhasil dihapus');
    }
}
