<?php
declare(strict_types=1);

namespace App\Modules\Carnets\Models;

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

class CarnetGuestEntry extends Model
{
    protected static string $table = 'carnet_guest_entries';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;

    protected static array $fillable = [
        'carnet_id', 'member_id', 'guest_name', 'guest_phone', 'guest_national_id',
        'guest_count', 'entry_date', 'entry_time', 'exit_time', 'facility_id',
        'activity_type', 'reservation_id', 'pool_booking_id', 'amount_paid',
        'payment_id', 'status', 'notes', 'recorded_by',
    ];

    public static function getActivityTypes(): array
    {
        return [
            'free_swim'      => 'سباحة ترفيهية',
            'court_booking'  => 'حجز ملعب',
            'recreation'     => 'ترفيه عام',
            'ping_pong'      => 'تنس طاولة',
            'bowling'        => 'بولينج',
            'playstation'    => 'بلاي ستيشن',
            'tennis'         => 'تنس',
            'paddle'         => 'بادل',
            'gym'            => 'جيم',
        ];
    }

    public static function getForCarnet(int $carnetId, ?string $dateFrom = null, ?string $dateTo = null): array
    {
        $db = App::getInstance()->db();
        $sql = "SELECT cge.*, f.name_ar AS facility_name
                FROM carnet_guest_entries cge
                LEFT JOIN facilities f ON f.id = cge.facility_id
                WHERE cge.carnet_id = ?";
        $params = [$carnetId];

        if ($dateFrom) {
            $sql .= " AND cge.entry_date >= ?";
            $params[] = $dateFrom;
        }
        if ($dateTo) {
            $sql .= " AND cge.entry_date <= ?";
            $params[] = $dateTo;
        }

        $sql .= " ORDER BY cge.entry_date DESC, cge.entry_time DESC";
        return $db->select($sql, $params);
    }

    public static function getForMember(int $memberId, int $limit = 50): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT cge.*, f.name_ar AS facility_name, c.carnet_number
             FROM carnet_guest_entries cge
             LEFT JOIN facilities f ON f.id = cge.facility_id
             LEFT JOIN carnets c ON c.id = cge.carnet_id
             WHERE cge.member_id = ?
             ORDER BY cge.entry_date DESC, cge.entry_time DESC
             LIMIT ?",
            [$memberId, $limit]
        );
    }

    public static function getTodayCount(int $carnetId): int
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne(
            "SELECT COALESCE(SUM(guest_count), 0) AS cnt FROM carnet_guest_entries WHERE carnet_id = ? AND entry_date = CURDATE() AND status != 'cancelled'",
            [$carnetId]
        );
        return (int) ($row['cnt'] ?? 0);
    }

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

        if (!empty($filters['member_id'])) {
            $where[] = "cge.member_id = ?";
            $params[] = (int) $filters['member_id'];
        }
        if (!empty($filters['facility_id'])) {
            $where[] = "cge.facility_id = ?";
            $params[] = (int) $filters['facility_id'];
        }
        if (!empty($filters['activity_type'])) {
            $where[] = "cge.activity_type = ?";
            $params[] = $filters['activity_type'];
        }
        if (!empty($filters['date_from'])) {
            $where[] = "cge.entry_date >= ?";
            $params[] = $filters['date_from'];
        }
        if (!empty($filters['date_to'])) {
            $where[] = "cge.entry_date <= ?";
            $params[] = $filters['date_to'];
        }
        if (!empty($filters['search'])) {
            $where[] = "(cge.guest_name LIKE ? OR cge.guest_phone LIKE ?)";
            $params[] = '%' . $filters['search'] . '%';
            $params[] = '%' . $filters['search'] . '%';
        }

        $whereClause = implode(' AND ', $where);

        $countRow = $db->selectOne(
            "SELECT COUNT(*) AS total FROM carnet_guest_entries cge WHERE {$whereClause}",
            $params
        );
        $total = (int) ($countRow['total'] ?? 0);

        $offset = ($page - 1) * $perPage;
        $data = $db->select(
            "SELECT cge.*, f.name_ar AS facility_name, c.carnet_number, m.full_name_ar AS member_name
             FROM carnet_guest_entries cge
             LEFT JOIN facilities f ON f.id = cge.facility_id
             LEFT JOIN carnets c ON c.id = cge.carnet_id
             LEFT JOIN members m ON m.id = cge.member_id
             WHERE {$whereClause}
             ORDER BY cge.entry_date DESC, cge.entry_time DESC
             LIMIT ? OFFSET ?",
            array_merge($params, [$perPage, $offset])
        );

        return [
            'data' => $data,
            'pagination' => [
                'total' => $total,
                'per_page' => $perPage,
                'current_page' => $page,
                'last_page' => (int) ceil($total / $perPage),
            ],
        ];
    }
}
