<?php
declare(strict_types=1);

namespace App\Modules\Documents\Models;

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

class Document extends Model
{
    protected static string $table = 'documents';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = true;
    protected static bool $dispatchEvents = true;
    protected static bool $autoTrackAuthor = false;

    protected static array $fillable = [
        'member_id', 'document_type', 'original_filename', 'stored_filename',
        'file_path', 'file_size', 'mime_type', 'related_entity_type',
        'related_entity_id', 'description', 'uploaded_by',
    ];

    public static function getForMember(int $memberId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT d.*, e.full_name_ar as uploaded_by_name
             FROM documents d LEFT JOIN employees e ON e.id = d.uploaded_by
             WHERE d.member_id = ? AND d.is_archived = 0 ORDER BY d.uploaded_at DESC",
            [$memberId]
        );
    }

    public static function getForEntity(string $entityType, int $entityId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM documents WHERE related_entity_type = ? AND related_entity_id = ? AND is_archived = 0 ORDER BY uploaded_at DESC",
            [$entityType, $entityId]
        );
    }

    public static function countForMember(int $memberId): int
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne("SELECT COUNT(*) as cnt FROM documents WHERE member_id = ? AND is_archived = 0", [$memberId]);
        return (int) ($row['cnt'] ?? 0);
    }

    public static function getDocumentTypes(): array
    {
        return [
            'national_id'        => 'صورة الرقم القومي',
            'birth_certificate'  => 'شهادة ميلاد',
            'marriage_certificate'=> 'عقد زواج',
            'divorce_certificate'=> 'وثيقة طلاق',
            'death_certificate'  => 'شهادة وفاة',
            'form_scan'          => 'نسخة الاستمارة',
            'qualification'      => 'شهادة المؤهل',
            'passport'           => 'صورة جواز السفر',
            'work_letter'        => 'خطاب العمل',
            'photo'              => 'صورة شخصية',
            'disability_doc'     => 'مستند إعاقة',
            'championship_doc'   => 'مستند بطولة',
            'medical_certificate'=> 'شهادة طبية',
            'fitness_cert'       => 'شهادة لياقة بدنية',
            'guardian_consent'   => 'موافقة ولي الأمر',
            'federation_card'    => 'كارنيه الاتحاد',
            'player_photo'       => 'صورة اللاعب',
            'rental_letter'      => 'خطاب رسمي للتأجير',
            'technical_report'   => 'تقرير فني',
            'contract_scan'      => 'نسخة عقد',
            'other'              => 'مستند آخر',
        ];
    }

    public static function getTypeLabel(string $type): string
    {
        $types = self::getDocumentTypes();
        return $types[$type] ?? $type;
    }

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

        if (!empty($filters['document_type'])) {
            $where .= ' AND d.document_type = ?';
            $params[] = $filters['document_type'];
        }
        if (!empty($filters['member_id'])) {
            $where .= ' AND d.member_id = ?';
            $params[] = (int) $filters['member_id'];
        }
        if (!empty($filters['search'])) {
            $where .= ' AND (m.full_name_ar LIKE ? OR d.original_filename LIKE ? OR d.description LIKE ?)';
            $s = '%' . $filters['search'] . '%';
            $params[] = $s; $params[] = $s; $params[] = $s;
        }

        $countRow = $db->selectOne("SELECT COUNT(*) as cnt FROM documents d JOIN members m ON m.id = d.member_id WHERE {$where}", $params);
        $total = (int) ($countRow['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;

        $rows = $db->select(
            "SELECT d.*, m.full_name_ar as member_name, m.membership_number, e.full_name_ar as uploaded_by_name
             FROM documents d JOIN members m ON m.id = d.member_id LEFT JOIN employees e ON e.id = d.uploaded_by
             WHERE {$where} ORDER BY d.uploaded_at DESC LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

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