<?php
/**
 * Simple Products API
 * Methods: GET, POST, PUT, DELETE
 */

// Start session
session_start();

// Include database connection
require_once '../controlls/functions.php';

// Set response headers
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

/**
 * Send JSON response
 */
function sendResponse($success, $message, $data = null) {
    $response = array(
        'success' => (bool)$success,
        'message' => $message
    );
    
    if ($data !== null) {
        $response['data'] = $data;
    }
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit();
}

/**
 * Check if user is logged in
 */
function checkAuth() {
    if (!isset($_SESSION['user_login'])) {
        sendResponse(false, 'Authentication required');
    }
    return $_SESSION['user_login'];
}

/**
 * Generate slug from text
 */
function generateSlug($text) {
    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9-]/', '-', $text);
    $text = preg_replace('/-+/', '-', $text);
    return trim($text, '-');
}

// Get request method
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        
        // ==================== GET - Retrieve Products ====================
        case 'GET':
            if (isset($_GET['id'])) {
                // Get single product
                $product_id = intval($_GET['id']);
                
                $stmt = $conn->prepare("SELECT * FROM products WHERE id = :id LIMIT 1");
                $stmt->bindParam(':id', $product_id, PDO::PARAM_INT);
                $stmt->execute();
                $product = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($product) {
                    // Get product images
                    $img_stmt = $conn->prepare("SELECT image_url FROM product_images WHERE product_id = :id ORDER BY is_primary DESC, sort_order ASC");
                    $img_stmt->execute([':id' => $product_id]);
                    $images = $img_stmt->fetchAll(PDO::FETCH_COLUMN);
                    $product['images'] = $images;
                    $product['primary_image'] = !empty($images) ? $images[0] : null;
                    
                    sendResponse(true, 'Product retrieved successfully', $product);
                } else {
                    sendResponse(false, 'Product not found');
                }
                
            } else {
                // Get all products with filters
                $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
                $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 20;
                $offset = ($page - 1) * $limit;
                
                // Build WHERE clause
                $where = array();
                $params = array();
                
                if (isset($_GET['search']) && !empty($_GET['search'])) {
                    $where[] = "(product_name LIKE :search OR sku LIKE :search OR brand LIKE :search)";
                    $params[':search'] = '%' . $_GET['search'] . '%';
                }
                
                if (isset($_GET['category']) && !empty($_GET['category'])) {
                    $where[] = "category = :category";
                    $params[':category'] = $_GET['category'];
                }
                
                if (isset($_GET['status']) && !empty($_GET['status'])) {
                    $where[] = "status = :status";
                    $params[':status'] = $_GET['status'];
                }
                
                $where_sql = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
                
                // Get total count
                $count_sql = "SELECT COUNT(*) as total FROM products $where_sql";
                $count_stmt = $conn->prepare($count_sql);
                foreach ($params as $key => $value) {
                    $count_stmt->bindValue($key, $value);
                }
                $count_stmt->execute();
                $total = $count_stmt->fetch(PDO::FETCH_ASSOC)['total'];
                
                // Get products
                $sql = "SELECT * FROM products $where_sql ORDER BY created_at DESC LIMIT :limit OFFSET :offset";
                $stmt = $conn->prepare($sql);
                foreach ($params as $key => $value) {
                    $stmt->bindValue($key, $value);
                }
                $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
                $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
                $stmt->execute();
                $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                // Get primary image for each product
                foreach ($products as &$product) {
                    $img_stmt = $conn->prepare("SELECT image_url FROM product_images WHERE product_id = :id ORDER BY is_primary DESC, sort_order ASC LIMIT 1");
                    $img_stmt->execute([':id' => $product['id']]);
                    $primary_image = $img_stmt->fetchColumn();
                    $product['primary_image'] = $primary_image ? $primary_image : null;
                }
                
                sendResponse(true, 'Products retrieved successfully', array(
                    'products' => $products,
                    'pagination' => array(
                        'current_page' => $page,
                        'per_page' => $limit,
                        'total' => $total,
                        'total_pages' => ceil($total / $limit)
                    )
                ));
            }
            break;
        
        // ==================== POST - Create Product ====================
        case 'POST':
            $user = checkAuth();
            
            // Get JSON data
            $json_input = file_get_contents('php://input');
            $input = json_decode($json_input, true);
            
            // Support form data as fallback
            if (empty($input)) {
                $input = $_POST;
            }
            
            // Validate required fields
            if (empty($input['product_name'])) {
                sendResponse(false, 'Product name is required');
            }
            if (empty($input['sku'])) {
                sendResponse(false, 'SKU is required');
            }
            if (empty($input['category'])) {
                sendResponse(false, 'Category is required');
            }
            if (!isset($input['regular_price'])) {
                sendResponse(false, 'Regular price is required');
            }
            
            // Generate slug
            $slug = generateSlug($input['product_name']);
            
            // Check if SKU already exists
            $check_sku = $conn->prepare("SELECT id FROM products WHERE sku = :sku");
            $check_sku->execute([':sku' => $input['sku']]);
            if ($check_sku->rowCount() > 0) {
                sendResponse(false, 'SKU already exists');
            }
            
            // Insert product
            $sql = "INSERT INTO products (
                product_name, slug, sku, brand, category, subcategory, 
                short_description, description, regular_price, sale_price, cost_price,
                stock_quantity, low_stock_alert, stock_status,
                weight, length, width, height, material, color, size, warranty, country_origin,
                meta_title, meta_description, tags,
                status, featured, show_homepage, allow_reviews, created_by
            ) VALUES (
                :product_name, :slug, :sku, :brand, :category, :subcategory,
                :short_description, :description, :regular_price, :sale_price, :cost_price,
                :stock_quantity, :low_stock_alert, :stock_status,
                :weight, :length, :width, :height, :material, :color, :size, :warranty, :country_origin,
                :meta_title, :meta_description, :tags,
                :status, :featured, :show_homepage, :allow_reviews, :created_by
            )";
            
            $stmt = $conn->prepare($sql);
            
            // Bind parameters with defaults
            $stmt->bindValue(':product_name', $input['product_name']);
            $stmt->bindValue(':slug', $slug);
            $stmt->bindValue(':sku', $input['sku']);
            $stmt->bindValue(':brand', isset($input['brand']) ? $input['brand'] : '');
            $stmt->bindValue(':category', $input['category']);
            $stmt->bindValue(':subcategory', isset($input['subcategory']) ? $input['subcategory'] : '');
            $stmt->bindValue(':short_description', isset($input['short_description']) ? $input['short_description'] : '');
            $stmt->bindValue(':description', isset($input['description']) ? $input['description'] : '');
            $stmt->bindValue(':regular_price', $input['regular_price']);
            $stmt->bindValue(':sale_price', isset($input['sale_price']) ? $input['sale_price'] : 0);
            $stmt->bindValue(':cost_price', isset($input['cost_price']) ? $input['cost_price'] : 0);
            $stmt->bindValue(':stock_quantity', isset($input['stock_quantity']) ? $input['stock_quantity'] : 0);
            $stmt->bindValue(':low_stock_alert', isset($input['low_stock_alert']) ? $input['low_stock_alert'] : 0);
            $stmt->bindValue(':stock_status', isset($input['stock_status']) ? $input['stock_status'] : 'in_stock');
            $stmt->bindValue(':weight', isset($input['weight']) ? $input['weight'] : '');
            $stmt->bindValue(':length', isset($input['length']) ? $input['length'] : '');
            $stmt->bindValue(':width', isset($input['width']) ? $input['width'] : '');
            $stmt->bindValue(':height', isset($input['height']) ? $input['height'] : '');
            $stmt->bindValue(':material', isset($input['material']) ? $input['material'] : '');
            $stmt->bindValue(':color', isset($input['color']) ? $input['color'] : '');
            $stmt->bindValue(':size', isset($input['size']) ? $input['size'] : '');
            $stmt->bindValue(':warranty', isset($input['warranty']) ? $input['warranty'] : '');
            $stmt->bindValue(':country_origin', isset($input['country_origin']) ? $input['country_origin'] : '');
            $stmt->bindValue(':meta_title', isset($input['meta_title']) ? $input['meta_title'] : '');
            $stmt->bindValue(':meta_description', isset($input['meta_description']) ? $input['meta_description'] : '');
            $stmt->bindValue(':tags', isset($input['tags']) ? $input['tags'] : '');
            $stmt->bindValue(':status', isset($input['status']) ? $input['status'] : 'active');
            $stmt->bindValue(':featured', isset($input['featured']) ? $input['featured'] : 0);
            $stmt->bindValue(':show_homepage', isset($input['show_homepage']) ? 1 : 0, PDO::PARAM_INT);
            $stmt->bindValue(':allow_reviews', isset($input['allow_reviews']) ? 1 : 0, PDO::PARAM_INT);
            $stmt->bindValue(':created_by', $user['id']);
            
            if ($stmt->execute()) {
                $product_id = $conn->lastInsertId();
                
                // Handle images if provided
                if (isset($input['images']) && is_array($input['images'])) {
                    $img_stmt = $conn->prepare("INSERT INTO product_images (product_id, image_url, is_primary, sort_order) VALUES (:product_id, :image_url, :is_primary, :sort_order)");
                    
                    foreach ($input['images'] as $index => $image_url) {
                        $is_primary = ($index === 0) ? 1 : 0;
                        $img_stmt->execute([
                            ':product_id' => $product_id,
                            ':image_url' => $image_url,
                            ':is_primary' => $is_primary,
                            ':sort_order' => $index
                        ]);
                    }
                }
                
                sendResponse(true, 'Product created successfully', array('product_id' => $product_id));
            } else {
                sendResponse(false, 'Failed to create product');
            }
            break;
        
        // ==================== PUT - Update Product ====================
        case 'PUT':
            $user = checkAuth();
            
            if (!isset($_GET['id'])) {
                sendResponse(false, 'Product ID is required');
            }
            
            $product_id = intval($_GET['id']);
            
            // Check if product exists
            $check = $conn->prepare("SELECT id FROM products WHERE id = :id");
            $check->execute([':id' => $product_id]);
            
            if ($check->rowCount() === 0) {
                sendResponse(false, 'Product not found');
            }
            
            // Get JSON data
            $json_input = file_get_contents('php://input');
            $input = json_decode($json_input, true);
            
            // Build update query dynamically
            $update_fields = array();
            $params = array(':id' => $product_id, ':updated_by' => $user['id']);
            
            $allowed_fields = array(
                'product_name', 'sku', 'brand', 'category', 'subcategory',
                'short_description', 'description', 'regular_price', 'sale_price', 'cost_price',
                'stock_quantity', 'low_stock_alert', 'stock_status',
                'weight', 'length', 'width', 'height', 'material', 'color', 'size', 'warranty', 'country_origin',
                'meta_title', 'meta_description', 'tags',
                'status', 'featured', 'show_homepage', 'allow_reviews'
            );
            
            foreach ($allowed_fields as $field) {
                if (isset($input[$field])) {
                    $update_fields[] = "$field = :$field";
                    $params[":$field"] = $input[$field];
                }
            }
            
            // Update slug if product name changed
            if (isset($input['product_name'])) {
                $slug = generateSlug($input['product_name']);
                $update_fields[] = "slug = :slug";
                $params[':slug'] = $slug;
            }
            
            $update_fields[] = "updated_by = :updated_by";
            
            if (count($update_fields) <= 1) {
                sendResponse(false, 'No fields to update');
            }
            
            $sql = "UPDATE products SET " . implode(', ', $update_fields) . " WHERE id = :id";
            $stmt = $conn->prepare($sql);
            
            foreach ($params as $key => $value) {
                $stmt->bindValue($key, $value);
            }
            
            if ($stmt->execute()) {
                sendResponse(true, 'Product updated successfully', array('product_id' => $product_id));
            } else {
                sendResponse(false, 'Failed to update product');
            }
            break;
        
        // ==================== DELETE - Delete Product ====================
        case 'DELETE':
            $user = checkAuth();
            
            if (!isset($_GET['id'])) {
                sendResponse(false, 'Product ID is required');
            }
            
            $product_id = intval($_GET['id']);
            
            // Delete product
            $stmt = $conn->prepare("DELETE FROM products WHERE id = :id");
            $stmt->execute([':id' => $product_id]);
            
            if ($stmt->rowCount() > 0) {
                sendResponse(true, 'Product deleted successfully');
            } else {
                sendResponse(false, 'Product not found');
            }
            break;
        
        default:
            sendResponse(false, 'Method not allowed');
            break;
    }
    
} catch (PDOException $e) {
    sendResponse(false, 'Database error: ' . $e->getMessage());
} catch (Exception $e) {
    sendResponse(false, 'Server error: ' . $e->getMessage());
}