<?php
/**
 * Admin Products API
 * CRUD operations for products
 */

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/Database.php';
require_once __DIR__ . '/../../includes/Auth.php';
require_once __DIR__ . '/../../includes/Product.php';

header('Content-Type: application/json');

// Check admin authentication
$auth = new Auth();
if (!$auth->isAdmin()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$product = new Product();
$db = Database::getInstance();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            if ($action === 'list') {
                $page = $_GET['page'] ?? 1;
                $perPage = $_GET['per_page'] ?? 20;
                $search = $_GET['search'] ?? '';
                
                $filters = [
                    'page' => $page,
                    'per_page' => $perPage,
                    'search' => $search
                ];
                
                $products = $product->getProducts($filters);
                $total = $product->getProductsCount($filters);
                
                echo json_encode([
                    'success' => true,
                    'products' => $products,
                    'total' => $total,
                    'page' => $page,
                    'per_page' => $perPage
                ]);
            } elseif ($action === 'get') {
                $id = $_GET['id'] ?? 0;
                $productData = $product->getProductById($id);
                
                if ($productData) {
                    echo json_encode(['success' => true, 'product' => $productData]);
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'Product not found']);
                }
            }
            break;

        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            
            if ($action === 'create') {
                // Generate slug if not provided
                if (empty($data['slug']) && !empty($data['name'])) {
                    $data['slug'] = $this->generateSlug($data['name']);
                }
                
                $db->execute(
                    "INSERT INTO products (name, slug, description, short_description, sku, price, sale_price,
                                          stock_quantity, category_id, supplier_id, image, is_gift, is_active)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                    [
                        $data['name'],
                        $data['slug'],
                        $data['description'] ?? null,
                        $data['short_description'] ?? null,
                        $data['sku'] ?? null,
                        $data['price'],
                        $data['sale_price'] ?? null,
                        $data['stock_quantity'] ?? 0,
                        $data['category_id'] ?? null,
                        $data['supplier_id'] ?? null,
                        $data['image'] ?? null,
                        isset($data['is_gift']) ? (int)$data['is_gift'] : 0,
                        isset($data['is_active']) ? (int)$data['is_active'] : 1
                    ]
                );
                
                $productId = $db->lastInsertId();
                echo json_encode(['success' => true, 'product_id' => $productId]);
            } elseif ($action === 'update') {
                $id = $data['id'] ?? 0;
                
                $db->execute(
                    "UPDATE products SET 
                        name = ?, slug = ?, description = ?, short_description = ?, sku = ?,
                        price = ?, sale_price = ?, stock_quantity = ?, category_id = ?,
                        supplier_id = ?, image = ?, is_gift = ?, is_active = ?, updated_at = NOW()
                     WHERE id = ?",
                    [
                        $data['name'],
                        $data['slug'],
                        $data['description'] ?? null,
                        $data['short_description'] ?? null,
                        $data['sku'] ?? null,
                        $data['price'],
                        $data['sale_price'] ?? null,
                        $data['stock_quantity'] ?? 0,
                        $data['category_id'] ?? null,
                        $data['supplier_id'] ?? null,
                        $data['image'] ?? null,
                        isset($data['is_gift']) ? (int)$data['is_gift'] : 0,
                        isset($data['is_active']) ? (int)$data['is_active'] : 1,
                        $id
                    ]
                );
                
                echo json_encode(['success' => true]);
            } elseif ($action === 'delete') {
                $id = $data['id'] ?? 0;
                $db->execute("DELETE FROM products WHERE id = ?", [$id]);
                echo json_encode(['success' => true]);
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

