<?php
require_once 'Database.php';

class Shop {
    private $db;

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

    public function createShop($owner_id, $data) {
        $stmt = $this->db->query(
            "INSERT INTO shops (owner_id, name, description, location, latitude, longitude, image) 
             VALUES (?, ?, ?, ?, ?, ?, ?)",
            [
                $owner_id,
                $data['name'],
                $data['description'] ?? '',
                $data['location'],
                $data['latitude'] ?? null,
                $data['longitude'] ?? null,
                $data['image'] ?? null
            ]
        );

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

    public function getActiveShops($searchTerm = null) {
        $sql = "SELECT s.*, u.name as owner_name 
                FROM shops s 
                JOIN users u ON s.owner_id = u.id 
                WHERE s.is_approved = TRUE";
        
        $params = [];

        if ($searchTerm) {
            $sql .= " AND (s.name LIKE ? OR s.location LIKE ?)";
            $likeTerm = '%' . $searchTerm . '%';
            $params[] = $likeTerm;
            $params[] = $likeTerm;
        }

        $sql .= " ORDER BY s.created_at DESC";

        $stmt = $this->db->query($sql, $params);

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

    public function getUserShops($owner_id) {
        $stmt = $this->db->query(
            "SELECT * FROM shops WHERE owner_id = ? ORDER BY created_at DESC",
            [$owner_id]
        );

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

    public function getShopById($shop_id) {
        $stmt = $this->db->query(
            "SELECT s.*, u.name as owner_name 
             FROM shops s 
             JOIN users u ON s.owner_id = u.id 
             WHERE s.id = ? AND s.is_approved = TRUE",
            [$shop_id]
        );

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function getProductById($product_id) {
        $stmt = $this->db->query(
            "SELECT p.*, s.owner_id 
             FROM products p
             JOIN shops s ON p.shop_id = s.id
             WHERE p.id = ?",
            [$product_id]
        );

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function addProduct($shop_id, $data) {
        $stmt = $this->db->query(
            "INSERT INTO products (shop_id, name, description, price, image, category) 
             VALUES (?, ?, ?, ?, ?, ?)",
            [
                $shop_id,
                $data['name'],
                $data['description'] ?? '',
                $data['price'],
                $data['image'] ?? null,
                $data['category'] ?? 'General'
            ]
        );

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

    public function getShopProducts($shop_id) {
        $stmt = $this->db->query(
            "SELECT * FROM products 
             WHERE shop_id = ?
             ORDER BY created_at DESC",
            [$shop_id]
        );

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

    public function getShopOrders($shop_id) {
        $stmt = $this->db->query(
            "SELECT o.*, u.name as customer_name 
             FROM orders o
             JOIN users u ON o.user_id = u.id
             WHERE o.shop_id = ?
             ORDER BY o.created_at DESC",
            [$shop_id]
        );
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function updateShop($shop_id, $owner_id, $data) {
        $fields = [];
        $params = [];

        foreach ($data as $key => $value) {
            if (!is_null($value)) {
                $fields[] = "{$key} = ?";
                $params[] = $value;
            }
        }

        if (empty($fields)) {
            return true; // Nothing to update
        }

        $params[] = $shop_id;
        // We don't need to check owner_id here as it's done in the API controller
        $stmt = $this->db->query("UPDATE shops SET " . implode(', ', $fields) . " WHERE id = ?", $params);

        return $stmt->rowCount() > 0;
    }

    public function updateProduct($product_id, $data)
    {
        $fields = [];
        $params = [];

        foreach ($data as $key => $value) {
            if (!is_null($value)) {
                $fields[] = "{$key} = ?";
                $params[] = $value;
            }
        }

        if (empty($fields)) {
            return true; // Nothing to update
        }

        $params[] = $product_id;
        $stmt = $this->db->query("UPDATE products SET " . implode(', ', $fields) . " WHERE id = ?", $params);

        return $stmt->rowCount() > 0;
    }

    public function setProductAvailability($product_id, $is_available) {
        $stmt = $this->db->query(
            "UPDATE products SET is_available = ? WHERE id = ?",
            [$is_available, $product_id]
        );

        return $stmt->rowCount() > 0;
    }

    public function updateOrderStatus($order_id, $status, $shop_id) {
        // Ensure the order belongs to the shop before updating
        $stmt = $this->db->query(
            "UPDATE orders SET status = ? WHERE id = ? AND shop_id = ?",
            [$status, $order_id, $shop_id]
        );

        return $stmt->rowCount() > 0;
    }

    public function deleteProduct($product_id, $shop_id) {
        $stmt = $this->db->query(
            "DELETE FROM products WHERE id = ? AND shop_id = ?",
            [$product_id, $shop_id]
        );

        return $stmt->rowCount() > 0;
    }

    public function isOwner($shop_id, $user_id) {
        $stmt = $this->db->query(
            "SELECT id FROM shops WHERE id = ? AND owner_id = ?",
            [$shop_id, $user_id]
        );

        return $stmt->rowCount() > 0;
    }

    public function getShopStats() {
        $stmt = $this->db->query("SELECT COUNT(*) as total FROM shops WHERE is_approved = TRUE");
        return $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    }
}
?>