<?php
declare(strict_types=1);

namespace App\Modules\Interviews\Models;

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

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

    protected static array $fillable = [
        'member_id', 'form_submission_id', 'scheduled_date', 'scheduled_time',
        'location', 'rescheduled_from', 'reschedule_reason', 'reschedule_count',
        'decision', 'decision_notes', 'decision_date', 'board_member_names',
        'board_decision_reference', 'notification_sent', 'notification_sent_at',
        'workflow_instance_id', 'status',
    ];

    public static function getForMember(int $memberId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT i.*, m.full_name_ar as member_name, m.membership_number
             FROM interviews i JOIN members m ON m.id = i.member_id
             WHERE i.member_id = ? ORDER BY i.scheduled_date DESC",
            [$memberId]
        );
    }

    public static function getPendingForMember(int $memberId): ?array
    {
        $db = App::getInstance()->db();
        return $db->selectOne(
            "SELECT * FROM interviews WHERE member_id = ? AND decision = 'pending' ORDER BY scheduled_date DESC LIMIT 1",
            [$memberId]
        );
    }

    public static function getUpcoming(int $daysAhead = 7): array
    {
        $db = App::getInstance()->db();
        $futureDate = date('Y-m-d', strtotime("+{$daysAhead} days"));
        return $db->select(
            "SELECT i.*, m.full_name_ar as member_name, m.membership_number, m.phone_mobile
             FROM interviews i JOIN members m ON m.id = i.member_id
             WHERE i.decision = 'pending' AND i.scheduled_date BETWEEN CURDATE() AND ?
             ORDER BY i.scheduled_date ASC, i.scheduled_time ASC",
            [$futureDate]
        );
    }

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

        if (!empty($filters['status'])) {
            $where .= ' AND i.status = ?';
            $params[] = $filters['status'];
        }
        if (!empty($filters['decision'])) {
            $where .= ' AND i.decision = ?';
            $params[] = $filters['decision'];
        }
        if (!empty($filters['date_from'])) {
            $where .= ' AND i.scheduled_date >= ?';
            $params[] = $filters['date_from'];
        }
        if (!empty($filters['date_to'])) {
            $where .= ' AND i.scheduled_date <= ?';
            $params[] = $filters['date_to'];
        }
        if (!empty($filters['search'])) {
            $where .= ' AND (m.full_name_ar LIKE ? OR m.membership_number LIKE ?)';
            $s = '%' . $filters['search'] . '%';
            $params[] = $s;
            $params[] = $s;
        }

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

        $rows = $db->select(
            "SELECT i.*, m.full_name_ar as member_name, m.membership_number, m.phone_mobile
             FROM interviews i JOIN members m ON m.id = i.member_id
             WHERE {$where} ORDER BY i.scheduled_date DESC LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

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

    public static function getDecisionLabel(string $decision): string
    {
        return match ($decision) {
            'pending'  => 'في الانتظار',
            'accepted' => 'مقبول',
            'rejected' => 'مرفوض',
            default    => $decision,
        };
    }
}