<?php
require_once __DIR__ . '/../config.php';


class Product {
    private $pdo;
    
    public function __construct() {
        $this->pdo = getDBConnection();
    }
    
    // Create - Add new product
    public function create($data) {
        $stmt = $this->pdo->prepare("
            INSERT INTO products (name, description, price, category, image_url, stock_quantity, sizes, colors, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            $data['name'],
            $data['description'],
            $data['price'],
            $data['category'],
            $data['image_url'],
            $data['stock_quantity'],
            json_encode($data['sizes']),
            json_encode($data['colors']),
            isset($data['is_active']) ? 1 : 0
        ]);
        return ['success' => true, 'id' => $this->pdo->lastInsertId()];
    }
    
    // Read - Get all products (with optional filters)
    public function getAll($category = null, $search = null, $limit = null, $offset = 0) {
        $sql = "SELECT * FROM products WHERE is_active = 1";
        $params = [];
        
        if ($category) {
            $sql .= " AND category = ?";
            $params[] = $category;
        }
        
        if ($search) {
            $sql .= " AND (name LIKE ? OR description LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }
        
        $sql .= " ORDER BY created_at DESC";
        
        if ($limit) {
            $sql .= " LIMIT ? OFFSET ?";
            $params[] = $limit;
            $params[] = $offset;
        }
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        
        $products = $stmt->fetchAll();
        
        // Decode JSON fields
        foreach ($products as &$product) {
            $product['sizes'] = json_decode($product['sizes'], true);
            $product['colors'] = json_decode($product['colors'], true);
        }
        
        return $products;
    }
    
    // Read - Get single product by ID
    public function getById($id) {
        $stmt = $this->pdo->prepare("SELECT * FROM products WHERE id = ?");
        $stmt->execute([$id]);
        $product = $stmt->fetch();
        
        if ($product) {
            $product['sizes'] = json_decode($product['sizes'], true);
            $product['colors'] = json_decode($product['colors'], true);
        }
        
        return $product;
    }
    
    // Read - Get all products (including inactive) for admin
    public function getAllAdmin($search = null) {
        $sql = "SELECT * FROM products ORDER BY created_at DESC";
        $params = [];
        
        if ($search) {
            $sql = "SELECT * FROM products WHERE name LIKE ? OR description LIKE ? ORDER BY created_at DESC";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        
        $products = $stmt->fetchAll();
        
        foreach ($products as &$product) {
            $product['sizes'] = json_decode($product['sizes'], true);
            $product['colors'] = json_decode($product['colors'], true);
        }
        
        return $products;
    }
    
    // Update - Update product
    public function update($id, $data) {
        $stmt = $this->pdo->prepare("
            UPDATE products 
            SET name = ?, description = ?, price = ?, category = ?, image_url = ?, 
                stock_quantity = ?, sizes = ?, colors = ?, is_active = ?
            WHERE id = ?
        ");
        $stmt->execute([
            $data['name'],
            $data['description'],
            $data['price'],
            $data['category'],
            $data['image_url'],
            $data['stock_quantity'],
            json_encode($data['sizes']),
            json_encode($data['colors']),
            isset($data['is_active']) ? 1 : 0,
            $id
        ]);
        return ['success' => true, 'message' => 'Product updated successfully'];
    }
    
    // Delete - Soft delete (deactivate) product
    public function delete($id) {
        $stmt = $this->pdo->prepare("UPDATE products SET is_active = 0 WHERE id = ?");
        $stmt->execute([$id]);
        return ['success' => true, 'message' => 'Product deleted successfully'];
    }
    
    // Hard delete product
    public function hardDelete($id) {
        $stmt = $this->pdo->prepare("DELETE FROM products WHERE id = ?");
        $stmt->execute([$id]);
        return ['success' => true, 'message' => 'Product removed permanently'];
    }
    
    // Get categories
    public function getCategories() {
        $stmt = $this->pdo->query("SELECT DISTINCT category FROM products WHERE is_active = 1 ORDER BY category");
        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }
    
    // Get product count
    public function getCount($category = null) {
        $sql = "SELECT COUNT(*) FROM products WHERE is_active = 1";
        $params = [];
        
        if ($category) {
            $sql .= " AND category = ?";
            $params[] = $category;
        }
        
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchColumn();
    }
    
    // Update stock
    public function updateStock($id, $quantity) {
        $stmt = $this->pdo->prepare("UPDATE products SET stock_quantity = stock_quantity - ? WHERE id = ?");
        $stmt->execute([$quantity, $id]);
        return ['success' => true];
    }
}
