<?php
class NotificationSchedule
{
    private $conn;
    private $table_name = "notification_schedules";

    public $id;
    public $booking_id;
    public $type;
    public $scheduled_for;
    public $status;

    public function __construct($db)
    {
        $this->conn = $db;
    }

    public function create($booking_id, $type, $scheduled_for)
    {
        $query = "INSERT INTO " . $this->table_name . " SET booking_id=:booking_id, type=:type, scheduled_for=:scheduled_for";
        $stmt = $this->conn->prepare($query);

        $stmt->bindParam(":booking_id", $booking_id);
        $stmt->bindParam(":type", $type);
        $stmt->bindParam(":scheduled_for", $scheduled_for);

        return $stmt->execute();
    }

    public function cancelForBooking($booking_id)
    {
        $query = "UPDATE " . $this->table_name . " SET status='CANCELLED' WHERE booking_id=:booking_id AND status='SCHEDULED'";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(":booking_id", $booking_id);
        return $stmt->execute();
    }

    public function reschedule($booking_id, $type, $new_time)
    {
        // Cancel existing scheduled of same type
        $query = "UPDATE " . $this->table_name . " SET status='CANCELLED' WHERE booking_id=:booking_id AND type=:type AND status='SCHEDULED'";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(":booking_id", $booking_id);
        $stmt->bindParam(":type", $type);
        $stmt->execute();

        // Create new schedule
        return $this->create($booking_id, $type, $new_time);
    }

    public function getPending()
    {
        $query = "SELECT ns.*, b.guesthouse_id, g.name as guesthouse_name, u.fcm_token, u.name as user_name, b.entry_code
                  FROM " . $this->table_name . " ns
                  JOIN bookings b ON ns.booking_id = b.id
                  JOIN guesthouses g ON b.guesthouse_id = g.id
                  JOIN users u ON b.user_id = u.id
                  WHERE ns.status = 'SCHEDULED' 
                  AND ns.scheduled_for <= NOW() 
                  AND u.fcm_token IS NOT NULL 
                  AND u.push_enabled = 1";

        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function markAsSent($id)
    {
        $query = "UPDATE " . $this->table_name . " SET status='SENT' WHERE id=:id";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(":id", $id);
        return $stmt->execute();
    }
}
