<?php

namespace App\Controllers;

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

class AdminBiodata extends BaseController
{
    protected $biodataModel;

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

    public function index()
    {
        // Fetch the first biodata record (assuming single profile)
        $profile = $this->biodataModel->first();

        // If no profile exists, we can direct user to create one
        // or show an empty state in the index view.

        $data = [
            'title' => 'Biodata / CV',
            'profile' => $profile
        ];
        return view('admin/biodata/index', $data);
    }

    public function create()
    {
        // Check if profile already exists to prevent duplicates (optional but good)
        if ($this->biodataModel->countAllResults() > 0) {
            return redirect()->to(base_url('admin/biodata'))->with('error', 'Biodata sudah ada. Silakan edit yang sudah ada.');
        }

        $data = [
            'title' => 'Buat Biodata',
            'validation' => \Config\Services::validation()
        ];
        return view('admin/biodata/create', $data);
    }

    public function store()
    {
        if (
            !$this->validate([
                'name' => 'required',
                'email' => 'required|valid_email',
                'photo' => [
                    'rules' => 'max_size[photo,2048]|is_image[photo]|mime_in[photo,image/jpg,image/jpeg,image/png]',
                    'errors' => [
                        'max_size' => 'Ukuran gambar terlalu besar',
                        'is_image' => 'File bukan gambar',
                        'mime_in' => 'File bukan gambar'
                    ]
                ]
            ])
        ) {
            return redirect()->to(base_url('admin/biodata/create'))->withInput();
        }

        $photoName = null;
        $filePhoto = $this->request->getFile('photo');
        if ($filePhoto && $filePhoto->isValid() && !$filePhoto->hasMoved()) {
            $photoName = $filePhoto->getRandomName();
            $filePhoto->move('uploads/biodata', $photoName);
        }

        $this->biodataModel->save([
            'name' => $this->request->getPost('name'),
            'job_title' => $this->request->getPost('job_title'),
            'address' => $this->request->getPost('address'),
            'email' => $this->request->getPost('email'),
            'phone' => $this->request->getPost('phone'),
            'summary' => $this->request->getPost('summary'),
            'photo' => $photoName
        ]);

        return redirect()->to(base_url('admin/biodata'))->with('success', 'Biodata berhasil dibuat');
    }

    public function edit($id)
    {
        $profile = $this->biodataModel->find($id);

        if (!$profile) {
            return redirect()->to(base_url('admin/biodata'))->with('error', 'Data biodata tidak ditemukan.');
        }

        $data = [
            'title' => 'Edit Biodata',
            'profile' => $profile,
            'validation' => \Config\Services::validation()
        ];
        return view('admin/biodata/edit', $data);
    }

    public function update($id)
    {
        if (
            !$this->validate([
                'name' => 'required',
                'email' => 'required|valid_email',
                'photo' => [
                    'rules' => 'max_size[photo,2048]|is_image[photo]|mime_in[photo,image/jpg,image/jpeg,image/png]',
                    'errors' => [
                        'max_size' => 'Ukuran gambar terlalu besar',
                        'is_image' => 'File bukan gambar',
                        'mime_in' => 'File bukan gambar'
                    ]
                ]
            ])
        ) {
            return redirect()->to(base_url('admin/biodata/edit/' . $id))->withInput();
        }

        $data = [
            'id' => $id,
            'name' => $this->request->getPost('name'),
            'job_title' => $this->request->getPost('job_title'),
            'address' => $this->request->getPost('address'),
            'email' => $this->request->getPost('email'),
            'phone' => $this->request->getPost('phone'),
            'summary' => $this->request->getPost('summary'),
        ];

        $filePhoto = $this->request->getFile('photo');
        if ($filePhoto && $filePhoto->isValid() && !$filePhoto->hasMoved()) {
            $photoName = $filePhoto->getRandomName();
            $filePhoto->move('uploads/biodata', $photoName);
            $data['photo'] = $photoName;
        }

        $this->biodataModel->save($data);
        return redirect()->to(base_url('admin/biodata'))->with('success', 'Biodata berhasil diperbarui');
    }
    public function delete($id)
    {
        $profile = $this->biodataModel->find($id);
        if ($profile) {
            // Delete photo if exists
            if (!empty($profile['photo']) && file_exists('uploads/biodata/' . $profile['photo'])) {
                unlink('uploads/biodata/' . $profile['photo']);
            }
            $this->biodataModel->delete($id);
            return redirect()->to(base_url('admin/biodata'))->with('success', 'Biodata berhasil dihapus');
        }
        return redirect()->to(base_url('admin/biodata'))->with('error', 'Data tidak ditemukan');
    }
}
