<?php
require_once __DIR__ . '/../../inc/db.php';
require_once __DIR__ . '/../../inc/functions.php';

try {
    $user = validateToken($conn);
    
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Get all products with optional search and pagination
        $search = sanitizeInput($_GET['search'] ?? '');
        $page = intval($_GET['page'] ?? 1);
        $limit = intval($_GET['limit'] ?? 20);
        $offset = ($page - 1) * $limit;
        
        $whereClause = '';
        $params = [];
        $types = '';
        
        if (!empty($search)) {
            $whereClause = "WHERE name LIKE ? OR distributor LIKE ?";
            $searchTerm = "%$search%";
            $params = [$searchTerm, $searchTerm];
            $types = 'ss';
        }
        
        // Get total count
        $countSql = "SELECT COUNT(*) as total FROM products $whereClause";
        $countStmt = $conn->prepare($countSql);
        if (!empty($params)) {
            $countStmt->bind_param($types, ...$params);
        }
        $countStmt->execute();
        $totalCount = $countStmt->get_result()->fetch_assoc()['total'];
        
        // Get products
        $sql = "SELECT * FROM products $whereClause ORDER BY id DESC LIMIT ? OFFSET ?";
        $stmt = $conn->prepare($sql);
        
        if (!empty($params)) {
            $stmt->bind_param($types . 'ii', ...$params, $limit, $offset);
        } else {
            $stmt->bind_param('ii', $limit, $offset);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        $products = [];
        while ($row = $result->fetch_assoc()) {
            // Decode images JSON
            $row['images'] = json_decode($row['images'], true) ?: [];
            $products[] = $row;
        }
        
        sendResponse(true, 'Products retrieved successfully', [
            'products' => $products,
            'pagination' => [
                'current_page' => $page,
                'per_page' => $limit,
                'total' => $totalCount,
                'total_pages' => ceil($totalCount / $limit)
            ]
        ]);
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Add new product
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            $input = $_POST;
        }
        
        $name = sanitizeInput($input['name'] ?? '');
        $price = floatval($input['price'] ?? 0);
        $sell_price = floatval($input['sell_price'] ?? 0);
        $distributor = sanitizeInput($input['distributor'] ?? '');
        $hsn_code = sanitizeInput($input['hsn_code'] ?? '');
        $quantity = intval($input['quantity'] ?? 0);
        $details = sanitizeInput($input['details'] ?? '');
        $images = $input['images'] ?? [];
        
        if (empty($name) || $price <= 0 || $sell_price <= 0 || empty($distributor)) {
            sendResponse(false, 'Name, price, sell price, and distributor are required', null, 400);
        }
        
        $imagesJson = json_encode($images);
        
        $stmt = $conn->prepare("INSERT INTO products (name, price, sell_price, distributor, hsn_code, quantity, details, images) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sddssiss", $name, $price, $sell_price, $distributor, $hsn_code, $quantity, $details, $imagesJson);
        
        if ($stmt->execute()) {
            $productId = $conn->insert_id;
            sendResponse(true, 'Product added successfully', [
                'id' => $productId,
                'name' => $name,
                'price' => $price,
                'sell_price' => $sell_price,
                'distributor' => $distributor,
                'hsn_code' => $hsn_code,
                'quantity' => $quantity,
                'details' => $details,
                'images' => $images
            ]);
        } else {
            sendResponse(false, 'Failed to add product', null, 500);
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
        // Update product
        $input = json_decode(file_get_contents('php://input'), true);
        
        $id = intval($input['id'] ?? 0);
        $name = sanitizeInput($input['name'] ?? '');
        $price = floatval($input['price'] ?? 0);
        $sell_price = floatval($input['sell_price'] ?? 0);
        $distributor = sanitizeInput($input['distributor'] ?? '');
        $hsn_code = sanitizeInput($input['hsn_code'] ?? '');
        $quantity = intval($input['quantity'] ?? 0);
        $details = sanitizeInput($input['details'] ?? '');
        $images = $input['images'] ?? [];
        
        if (empty($id) || empty($name) || $price <= 0 || $sell_price <= 0 || empty($distributor)) {
            sendResponse(false, 'ID, name, price, sell price, and distributor are required', null, 400);
        }
        
        $imagesJson = json_encode($images);
        
        $stmt = $conn->prepare("UPDATE products SET name=?, price=?, sell_price=?, distributor=?, hsn_code=?, quantity=?, details=?, images=? WHERE id=?");
        $stmt->bind_param("sddssissi", $name, $price, $sell_price, $distributor, $hsn_code, $quantity, $details, $imagesJson, $id);
        
        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                sendResponse(true, 'Product updated successfully', [
                    'id' => $id,
                    'name' => $name,
                    'price' => $price,
                    'sell_price' => $sell_price,
                    'distributor' => $distributor,
                    'hsn_code' => $hsn_code,
                    'quantity' => $quantity,
                    'details' => $details,
                    'images' => $images
                ]);
            } else {
                sendResponse(false, 'Product not found', null, 404);
            }
        } else {
            sendResponse(false, 'Failed to update product', null, 500);
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
        // Delete product
        $input = json_decode(file_get_contents('php://input'), true);
        
        $id = intval($input['id'] ?? 0);
        
        if (empty($id)) {
            sendResponse(false, 'Product ID is required', null, 400);
        }
        
        $stmt = $conn->prepare("DELETE FROM products WHERE id = ?");
        $stmt->bind_param("i", $id);
        
        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                sendResponse(true, 'Product deleted successfully');
            } else {
                sendResponse(false, 'Product not found', null, 404);
            }
        } else {
            sendResponse(false, 'Failed to delete product', null, 500);
        }
    } else {
        sendResponse(false, 'Method not allowed', null, 405);
    }
    
} catch (Exception $e) {
    sendResponse(false, 'Operation failed: ' . $e->getMessage(), null, 500);
}
?>
