<?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();
    }

    /**
     * Edit biodata form
     */
    public function edit()
    {
        $biodata = $this->biodataModel->getBiodata();

        $data = [
            'title'   => 'Edit Biodata',
            'biodata' => $biodata,
        ];

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

    /**
     * Update biodata
     */
    public function update()
    {
        // Validation rules
        $rules = [
            'full_name'    => 'required|min_length[2]|max_length[100]',
            'headline'     => 'required|max_length[200]',
            'email_public' => 'required|valid_email',
            'location'     => 'permit_empty|max_length[100]',
            'phone_public' => 'permit_empty|max_length[20]',
            'linkedin_url' => 'permit_empty|valid_url_strict',
            'github_url'   => 'permit_empty|valid_url_strict',
            'portfolio_url'=> 'permit_empty|valid_url_strict',
        ];

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

        // Get form data
        $skills = $this->request->getPost('skills');
        $skillsArray = array_map('trim', explode(',', $skills));
        $skillsArray = array_filter($skillsArray);

        $data = [
            'full_name'     => $this->request->getPost('full_name'),
            'headline'      => $this->request->getPost('headline'),
            'location'      => $this->request->getPost('location'),
            'email_public'  => $this->request->getPost('email_public'),
            'phone_public'  => $this->request->getPost('phone_public'),
            'about'         => $this->request->getPost('about'),
            'skills'        => json_encode($skillsArray),
            'linkedin_url'  => $this->request->getPost('linkedin_url'),
            'github_url'    => $this->request->getPost('github_url'),
            'portfolio_url' => $this->request->getPost('portfolio_url'),
        ];

        // Handle photo upload
        $photo = $this->request->getFile('photo');
        if ($photo && $photo->isValid() && !$photo->hasMoved()) {
            // Validate file
            $validationRules = [
                'photo' => [
                    'uploaded[photo]',
                    'mime_in[photo,image/jpg,image/jpeg,image/png,image/webp]',
                    'max_size[photo,2048]',
                ],
            ];

            if ($this->validate($validationRules)) {
                // Generate random filename
                $newName = $photo->getRandomName();
                $photo->move(WRITEPATH . 'uploads/photos', $newName);
                $data['photo'] = 'photos/' . $newName;
            }
        }

        if ($this->biodataModel->saveBiodata($data)) {
            return redirect()->to('/admin/biodata')
                ->with('success', 'Biodata berhasil diperbarui.');
        }

        return redirect()->back()
            ->withInput()
            ->with('error', 'Gagal memperbarui biodata.');
    }
}
