<?php
class BeautyService {
    private $conn;
    private $table_name = "beauty_services";

    public $id = null;
    public $name = '';
    public $description = '';
    public $price = 0;
    public $discount_percentage = 0;
    public $final_price = 0;
    public $duration = 0;
    public $category = '';
    public $is_active = 1;
    public $image = '';
    public $available_branches = '[]';
    public $stock_quantity = 0;

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

    public function getAllServices() {
        $query = "SELECT * FROM " . $this->table_name . " WHERE is_active = 1 ORDER BY created_at DESC";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getServicesByCategory($category = null) {
        if ($category && $category !== 'all') {
            $query = "SELECT * FROM " . $this->table_name . " WHERE is_active = 1 AND category = ? ORDER BY created_at DESC";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(1, $category);
        } else {
            $query = "SELECT * FROM " . $this->table_name . " WHERE is_active = 1 ORDER BY created_at DESC";
            $stmt = $this->conn->prepare($query);
        }
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function searchServices($searchTerm) {
        $query = "SELECT * FROM " . $this->table_name . " WHERE is_active = 1 AND (name LIKE ? OR description LIKE ?) ORDER BY created_at DESC";
        $stmt = $this->conn->prepare($query);
        $searchPattern = "%" . $searchTerm . "%";
        $stmt->bindParam(1, $searchPattern);
        $stmt->bindParam(2, $searchPattern);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getServiceById($id) {
        $query = "SELECT * FROM " . $this->table_name . " WHERE id = ? AND is_active = 1";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $id);
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function getServiceBranches($serviceId) {
        // First get the available_branches JSON for this service
        $query1 = "SELECT available_branches FROM " . $this->table_name . " WHERE id = ?";
        $stmt1 = $this->conn->prepare($query1);
        $stmt1->bindParam(1, $serviceId);
        $stmt1->execute();
        $service = $stmt1->fetch(PDO::FETCH_ASSOC);

        if (!$service || empty($service['available_branches'])) {
            return [];
        }

        // Decode the JSON to get branch IDs
        $branchIds = json_decode($service['available_branches'], true);
        if (empty($branchIds) || !is_array($branchIds)) {
            return [];
        }

        // Get branch details for these IDs
        $placeholders = str_repeat('?,', count($branchIds) - 1) . '?';
        $query2 = "SELECT * FROM branches WHERE id IN ($placeholders) AND is_active = 1 ORDER BY name";
        $stmt2 = $this->conn->prepare($query2);

        // Execute with the branch IDs array
        $result = $stmt2->execute($branchIds);
        if (!$result) {
            return [];
        }

        return $stmt2->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getAllBranches() {
        $query = "SELECT * FROM branches WHERE is_active = 1 ORDER BY name";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function create() {
        // Calculate final_price based on discount_percentage
        $this->final_price = $this->price * (1 - ($this->discount_percentage / 100));

        $query = "INSERT INTO " . $this->table_name . "
                SET name=:name, description=:description, price=:price, discount_percentage=:discount_percentage,
                    duration=:duration, category=:category, image=:image, available_branches=:available_branches,
                    is_active=:is_active, stock_quantity=:stock_quantity, created_at=NOW(), updated_at=NOW()";

        $stmt = $this->conn->prepare($query);

        $this->name = htmlspecialchars(strip_tags($this->name));
        $this->description = htmlspecialchars(strip_tags($this->description));
        $this->price = htmlspecialchars(strip_tags($this->price));
        $this->discount_percentage = htmlspecialchars(strip_tags($this->discount_percentage ?? 0));
        $this->duration = htmlspecialchars(strip_tags($this->duration));
        $this->category = htmlspecialchars(strip_tags($this->category));
        $this->image = htmlspecialchars(strip_tags($this->image ?? ''));

        // Handle available_branches as JSON
        if (is_array($this->available_branches)) {
            $this->available_branches = json_encode($this->available_branches);
        } elseif ($this->available_branches === null || $this->available_branches === '') {
            $this->available_branches = '[]';
        }

        $this->is_active = $this->is_active ?? 1;
        $this->stock_quantity = $this->stock_quantity ?? 0;

        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":description", $this->description);
        $stmt->bindParam(":price", $this->price);
        $stmt->bindParam(":discount_percentage", $this->discount_percentage);
        $stmt->bindParam(":duration", $this->duration);
        $stmt->bindParam(":category", $this->category);
        $stmt->bindParam(":image", $this->image);
        $stmt->bindParam(":available_branches", $this->available_branches);
        $stmt->bindParam(":is_active", $this->is_active);
        $stmt->bindParam(":stock_quantity", $this->stock_quantity);

        if($stmt->execute()) {
            $this->id = $this->conn->lastInsertId();
            return true;
        }

        return false;
    }

    public function update() {
        // Calculate final_price based on discount_percentage
        $this->final_price = $this->price * (1 - ($this->discount_percentage / 100));

        $query = "UPDATE " . $this->table_name . "
                SET name=:name, description=:description, price=:price,
                    discount_percentage=:discount_percentage,
                    duration=:duration, category=:category, image=:image, available_branches=:available_branches,
                    is_active=:is_active, stock_quantity=:stock_quantity, updated_at=NOW()
                WHERE id=:id";

        $stmt = $this->conn->prepare($query);

        $this->name = htmlspecialchars(strip_tags($this->name));
        $this->description = htmlspecialchars(strip_tags($this->description));
        $this->price = htmlspecialchars(strip_tags($this->price));
        $this->duration = htmlspecialchars(strip_tags($this->duration));
        $this->category = htmlspecialchars(strip_tags($this->category));
        $this->image = htmlspecialchars(strip_tags($this->image ?? ''));

        // Handle available_branches as JSON
        if (is_array($this->available_branches)) {
            $this->available_branches = json_encode($this->available_branches);
        } elseif ($this->available_branches === null || $this->available_branches === '') {
            $this->available_branches = '[]';
        }

        $this->stock_quantity = $this->stock_quantity ?? 0;

        $stmt->bindParam(":name", $this->name);
        $stmt->bindParam(":description", $this->description);
        $stmt->bindParam(":price", $this->price);
        $stmt->bindParam(":discount_percentage", $this->discount_percentage);
        $stmt->bindParam(":duration", $this->duration);
        $stmt->bindParam(":category", $this->category);
        $stmt->bindParam(":image", $this->image);
        $stmt->bindParam(":available_branches", $this->available_branches);
        $stmt->bindParam(":is_active", $this->is_active);
        $stmt->bindParam(":stock_quantity", $this->stock_quantity);
        $stmt->bindParam(":id", $this->id);

        if($stmt->execute()) {
            return true;
        }

        return false;
    }

    public function delete() {
        $query = "UPDATE " . $this->table_name . " SET is_active = 0 WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->bindParam(1, $this->id);

        if($stmt->execute()) {
            return true;
        }

        return false;
    }
}
?>