<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\BiodataModel;

class BiodataController extends BaseController
{
    protected $biodataModel;

    public function __construct()
    {
        $this->biodataModel = new BiodataModel();
    }

    public function index()
    {
        $search = $this->request->getGet('search');

        $biodata = $this->biodataModel;

        if ($search) {
            $biodata = $biodata->like('field_key', $search)->orLike('field_value', $search);
        }

        $data = [
            'biodata' => $biodata->paginate(10), // No complex sort usually for key-value
            'pager' => $this->biodataModel->pager,
            'search' => $search,
        ];

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

    public function new()
    {
        return view('admin/biodata/form', ['title' => 'New Biodata Field']);
    }

    public function create()
    {
        if (
            !$this->validate([
                'field_key' => 'required|min_length[2]|is_unique[biodata.field_key]',
                'field_value' => 'required',
            ])
        ) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $this->biodataModel->save([
            'field_key' => $this->request->getPost('field_key'),
            'field_value' => $this->request->getPost('field_value'),
        ]);

        return redirect()->to('/admin/cv')->with('message', 'Field created successfully');
    }

    public function edit($id)
    {
        $item = $this->biodataModel->find($id);
        if (!$item) {
            return redirect()->to('/admin/cv')->with('error', 'Item not found');
        }

        return view('admin/biodata/form', ['item' => $item, 'title' => 'Edit Field']);
    }

    public function update($id)
    {
        $item = $this->biodataModel->find($id);

        if (
            !$this->validate([
                'field_key' => "required|min_length[2]|is_unique[biodata.field_key,id,{$id}]",
                'field_value' => 'required',
            ])
        ) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $this->biodataModel->save([
            'id' => $id,
            'field_key' => $this->request->getPost('field_key'),
            'field_value' => $this->request->getPost('field_value'),
        ]);

        return redirect()->to('/admin/cv')->with('message', 'Field updated successfully');
    }

    public function delete($id)
    {
        $this->biodataModel->delete($id);
        return redirect()->to('/admin/cv')->with('message', 'Field deleted successfully');
    }
}
