<?php

namespace App\Models;

use CodeIgniter\Model;

class BiodataModel extends Model
{
    protected $table            = 'biodata';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'full_name', 'headline', 'location', 'email_public', 'phone_public',
        'about', 'skills', 'photo', 'linkedin_url', 'github_url', 'portfolio_url'
    ];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Validation
    protected $validationRules = [
        '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]',
        'about'        => 'permit_empty',
        'linkedin_url' => 'permit_empty|valid_url',
        'github_url'   => 'permit_empty|valid_url',
        'portfolio_url'=> 'permit_empty|valid_url',
    ];

    protected $skipValidation = false;

    /**
     * Get the single biodata record (always ID = 1)
     */
    public function getBiodata(): ?array
    {
        $biodata = $this->first();
        
        if ($biodata && !empty($biodata['skills'])) {
            $biodata['skills_array'] = json_decode($biodata['skills'], true) ?? [];
        } else {
            $biodata['skills_array'] = [];
        }
        
        return $biodata;
    }

    /**
     * Update or create biodata
     */
    public function saveBiodata(array $data): bool
    {
        $existing = $this->first();
        
        // Convert skills array to JSON if provided as array
        if (isset($data['skills']) && is_array($data['skills'])) {
            $data['skills'] = json_encode($data['skills']);
        }
        
        if ($existing) {
            return $this->update($existing['id'], $data);
        }
        
        return $this->insert($data) !== false;
    }
}
