<?php

require_once BASE_PATH . '/config/database.php';

class BlockedSlot
{
    private PDO $db;

    public function __construct()
    {
        $this->db = (new Database())->connect();
    }

    public function getForOwner(string $fromDate = ''): array
    {
        $params = [];
        $where = '';

        if ($fromDate !== '') {
            $where = 'WHERE bs.blocked_date >= :from_date';
            $params['from_date'] = $fromDate;
        }

        $stmt = $this->db->prepare(
            "SELECT bs.*, u.full_name AS creator_name
             FROM blocked_slots bs
             LEFT JOIN users u ON u.id = bs.created_by
             {$where}
             ORDER BY bs.blocked_date ASC, bs.start_time ASC, bs.id ASC"
        );
        $stmt->execute($params);

        return $stmt->fetchAll();
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare(
            'INSERT INTO blocked_slots (
                blocked_date, start_time, end_time, reason, created_by
             ) VALUES (
                :blocked_date, :start_time, :end_time, :reason, :created_by
             )'
        );
        $stmt->execute($data);

        return (int) $this->db->lastInsertId();
    }

    public function findById(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM blocked_slots WHERE id = :id LIMIT 1');
        $stmt->execute(['id' => $id]);
        $slot = $stmt->fetch();

        return $slot ?: null;
    }

    public function delete(int $id): void
    {
        $stmt = $this->db->prepare('DELETE FROM blocked_slots WHERE id = :id');
        $stmt->execute(['id' => $id]);
    }
}
