<?php

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

class Service
{
    private PDO $db;

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

    public function getPublic(string $search = '', string $categorySlug = ''): array
    {
        $where = 's.is_active = 1
                  AND (s.category_id IS NULL OR sc.is_active = 1)';
        $params = [];

        if ($search !== '') {
            $where .= ' AND (s.name LIKE :service_search
                              OR s.short_description LIKE :description_search)';
            $params['service_search'] = '%' . $search . '%';
            $params['description_search'] = '%' . $search . '%';
        }

        if ($categorySlug !== '') {
            $where .= ' AND sc.slug = :category_slug';
            $params['category_slug'] = $categorySlug;
        }

        $stmt = $this->db->prepare(
            "SELECT s.*, sc.name AS category_name, sc.slug AS category_slug
             FROM services s
             LEFT JOIN service_categories sc ON sc.id = s.category_id
             WHERE {$where}
             ORDER BY s.sort_order ASC, s.name ASC"
        );
        $stmt->execute($params);

        return $stmt->fetchAll();
    }

    public function findActiveBySlug(string $slug): ?array
    {
        $stmt = $this->db->prepare(
            "SELECT s.*, sc.name AS category_name, sc.slug AS category_slug
             FROM services s
             LEFT JOIN service_categories sc ON sc.id = s.category_id
             WHERE s.slug = :slug
               AND s.is_active = 1
               AND (s.category_id IS NULL OR sc.is_active = 1)
             LIMIT 1"
        );
        $stmt->execute(['slug' => $slug]);
        $row = $stmt->fetch();

        return $row ?: null;
    }

    public function findActiveById(int $id): ?array
    {
        $stmt = $this->db->prepare(
            "SELECT s.*, sc.name AS category_name
             FROM services s
             LEFT JOIN service_categories sc ON sc.id = s.category_id
             WHERE s.id = :id
               AND s.is_active = 1
               AND (s.category_id IS NULL OR sc.is_active = 1)
             LIMIT 1"
        );
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch();

        return $row ?: null;
    }

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

        if ($search !== '') {
            $where .= ' AND (s.name LIKE :service_search OR s.slug LIKE :slug_search)';
            $params['service_search'] = '%' . $search . '%';
            $params['slug_search'] = '%' . $search . '%';
        }

        $stmt = $this->db->prepare(
            "SELECT s.*, sc.name AS category_name
             FROM services s
             LEFT JOIN service_categories sc ON sc.id = s.category_id
             WHERE {$where}
             ORDER BY s.sort_order ASC, s.name ASC"
        );
        $stmt->execute($params);

        return $stmt->fetchAll();
    }

    public function findForOwner(int $id): ?array
    {
        $stmt = $this->db->prepare(
            "SELECT s.*, sc.name AS category_name
             FROM services s
             LEFT JOIN service_categories sc ON sc.id = s.category_id
             WHERE s.id = :id
             LIMIT 1"
        );
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch();

        return $row ?: null;
    }

    public function slugExists(string $slug, ?int $excludeId = null): bool
    {
        $sql = 'SELECT 1 FROM services WHERE slug = :slug';
        $params = ['slug' => $slug];
        if ($excludeId !== null) {
            $sql .= ' AND id != :id';
            $params['id'] = $excludeId;
        }
        $stmt = $this->db->prepare($sql . ' LIMIT 1');
        $stmt->execute($params);
        return (bool) $stmt->fetchColumn();
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare(
            'INSERT INTO services (
                category_id, name, slug, short_description, description,
                price, duration_minutes, featured_image, is_active, sort_order
             ) VALUES (
                :category_id, :name, :slug, :short_description, :description,
                :price, :duration_minutes, :featured_image, :is_active, :sort_order
             )'
        );
        $stmt->execute($data);

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

    public function update(int $id, array $data): void
    {
        $data['id'] = $id;
        $stmt = $this->db->prepare(
            'UPDATE services
             SET category_id = :category_id, name = :name, slug = :slug,
                 short_description = :short_description, description = :description,
                 price = :price, duration_minutes = :duration_minutes,
                 featured_image = :featured_image, is_active = :is_active,
                 sort_order = :sort_order
             WHERE id = :id'
        );
        $stmt->execute($data);
    }

    public function toggle(int $id): void
    {
        $stmt = $this->db->prepare(
            'UPDATE services
             SET is_active = IF(is_active = 1, 0, 1)
             WHERE id = :id'
        );
        $stmt->execute(['id' => $id]);
    }
}
