<?php

include_once 'config.php';
class service_model
{
    public $link;

    public function __construct()
    {
        $db_connection = new dbConnection();
        $this->link = $db_connection->connect();
    }

    public function getActiveServices(){
        $sql = "SELECT service_code, service_name, service_cost, duration, service_image, short_description FROM spa_services WHERE service_state = 1";
        $smtp = $this->link->prepare($sql);

        $smtp->execute();
        $services = $smtp->fetchAll(PDO::FETCH_ASSOC);

        return $services;
    }

    public function getBookedTimeSlots($date){
        $stmt = $this->link->prepare("SELECT time_slot FROM spa_bookings WHERE appointment_date = ? AND booking_state = 2");
        $stmt->execute([$date]);
        $times = $stmt->fetchAll(PDO::FETCH_COLUMN);

        // Trim seconds from "HH:mm:ss" to "HH:mm"
        $normalized = array_map(function($time) {
            return substr($time, 0, 5);
        }, $times);

        return $normalized;
    }

    public function captureBooking($name, $sex, $phone, $email, $notes, $service, $date, $time, $cost) {
        try {
            $sql = "INSERT INTO spa_bookings (fullname, sex, phone_number, email, service_code, appointment_date, time_slot, cost, booking_notes) VALUES (:name, :sex, :phone, :email, :service, :date, :time, :cost, :notes)";

            $stmt = $this->link->prepare($sql);

            $stmt->execute([ ':name'    => $name, ':sex'     => $sex, ':phone'   => $phone, ':email'   => $email, ':service' => $service, ':date'    => $date, ':time'    => $time, ':cost'    => $cost, ':notes'   => $notes]);

            return true;

        } catch (PDOException $e) {
            error_log("Booking error: " . $e->getMessage());
            return false;
        }
    }

    public function getServiceDetailsByName($name) {
        try {
            $sql = "SELECT * FROM spa_services WHERE service_name = :name LIMIT 1";
            $stmt = $this->link->prepare($sql);
            $stmt->execute([':name' => $name]);

            if ($stmt->rowCount() > 0) {
                return $stmt->fetch(PDO::FETCH_ASSOC);
            } else {
                return null; // No match found
            }

        } catch (PDOException $e) {
            error_log("Error fetching service details by name: " . $e->getMessage());
            return false;
        }

        
    }

    

    public function getServices(){
        $sql = "SELECT * FROM spa_services WHERE service_state = 1";
        $smtp = $this->link->prepare($sql);

        $smtp->execute();
        $services = $smtp->fetchAll(PDO::FETCH_ASSOC);
        return $services;

    }

}

?>
