<?php
declare(strict_types=1);

namespace App\Modules\Forms\Models;

use App\Core\Model;
use App\Core\App;
use App\Core\Pagination;

class FormSubmission extends Model
{
    protected static string $table = 'form_submissions';
    protected static bool $softDelete = false;
    protected static bool $timestamps = true;
    protected static array $fillable = [
        'form_schema_id', 'schema_version', 'form_number', 'submitted_data_json',
        'status', 'submitted_by_employee_id', 'member_id', 'expires_at',
        'fee_receipt_number', 'notes',
    ];

    public function getData(): array
    {
        return json_decode($this->submitted_data_json ?? '{}', true) ?? [];
    }

    public static function generateFormNumber(string $formCode): string
    {
        $db = App::getInstance()->db();
        $prefix = strtoupper(substr($formCode, 0, 3));
        $year = date('Y');
        $pattern = $prefix . '-' . $year . '-%';
        $last = $db->selectOne(
            "SELECT form_number FROM form_submissions WHERE form_number LIKE ? ORDER BY id DESC LIMIT 1",
            [$pattern]
        );
        if ($last) {
            $parts = explode('-', $last['form_number']);
            $seq = (int) end($parts) + 1;
        } else {
            $seq = 1;
        }
        return $prefix . '-' . $year . '-' . str_pad((string) $seq, 5, '0', STR_PAD_LEFT);
    }

    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = '1=1';
        $params = [];

        if (!empty($filters['form_code'])) {
            $where .= ' AND fs.form_code = ?';
            $params[] = $filters['form_code'];
        }
        if (!empty($filters['status'])) {
            $where .= ' AND sub.status = ?';
            $params[] = $filters['status'];
        }
        if (!empty($filters['search'])) {
            $where .= ' AND (sub.form_number LIKE ? OR sub.notes LIKE ?)';
            $s = '%' . $filters['search'] . '%';
            $params[] = $s;
            $params[] = $s;
        }
        if (!empty($filters['date_from'])) {
            $where .= ' AND sub.created_at >= ?';
            $params[] = $filters['date_from'] . ' 00:00:00';
        }
        if (!empty($filters['date_to'])) {
            $where .= ' AND sub.created_at <= ?';
            $params[] = $filters['date_to'] . ' 23:59:59';
        }

        $countRow = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM form_submissions sub JOIN form_schemas fs ON fs.id = sub.form_schema_id WHERE {$where}",
            $params
        );
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT sub.*, fs.form_code, fs.name_ar as schema_name_ar, e.full_name_ar as employee_name
             FROM form_submissions sub
             JOIN form_schemas fs ON fs.id = sub.form_schema_id
             LEFT JOIN employees e ON e.id = sub.submitted_by_employee_id
             WHERE {$where}
             ORDER BY sub.created_at DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        $pagination = Pagination::paginate($total, $perPage, $page);
        return ['data' => $rows, 'pagination' => $pagination];
    }
}