<?php
include 'bd/myData.php';
require_once 'auth.php';
include 'cors.php';
setupCORS();

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

requireAuth();

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    requirePermission('article', 'view');
    try {
        // Case 1: Lookup by id_produit
        if (isset($_GET['id_produit'])) {
            $query = "SELECT p.*, c.nom_categorie AS famille_desc, m.description AS marque_desc 
                     FROM produits p 
                     JOIN categories c ON p.id_categorie = c.id_categorie 
                     JOIN marque m ON p.id_marque = m.id_marque 
                     WHERE p.id_produit = :id_produit";
            $params = array(':id_produit' => $_GET['id_produit']);
            $result = metodGet($query, $params);
            $data = $result->fetchAll(PDO::FETCH_ASSOC);

            if (empty($data)) {
                http_response_code(404);
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Product not found',
                    'code' => 'PRODUCT_NOT_FOUND'
                ]);
                exit();
            }

            http_response_code(200);
            echo json_encode($data);
            exit();
        }

        // Case 2: Lookup by reference (exact match for barcode scanning)
        if (isset($_GET['reference'])) {
            $query = "SELECT p.*, c.nom_categorie AS famille_desc, m.description AS marque_desc 
                     FROM produits p 
                     JOIN categories c ON p.id_categorie = c.id_categorie 
                     JOIN marque m ON p.id_marque = m.id_marque 
                     WHERE p.reference = :reference";
            $params = array(':reference' => $_GET['reference']);
            $result = metodGet($query, $params);
            $data = $result->fetchAll(PDO::FETCH_ASSOC);

            if (empty($data)) {
                http_response_code(404);
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Product not found with reference: ' . $_GET['reference'],
                    'code' => 'REFERENCE_NOT_FOUND'
                ]);
                exit();
            }

            http_response_code(200);
            echo json_encode($data);
            exit();
        }

        // Case 3: Search by category
        if (isset($_GET['id_categorie'])) {
            $query = "SELECT p.*, c.nom_categorie AS famille_desc, m.description AS marque_desc 
                     FROM produits p 
                     JOIN categories c ON p.id_categorie = c.id_categorie 
                     JOIN marque m ON p.id_marque = m.id_marque 
                     WHERE p.id_categorie = :id_categorie";
            $params = array(':id_categorie' => $_GET['id_categorie']);
            $result = metodGet($query, $params);
            $data = $result->fetchAll(PDO::FETCH_ASSOC);

            http_response_code(200);
            echo json_encode($data);
            exit();
        }

        // Case 4: Search by brand
        if (isset($_GET['id_marque'])) {
            $query = "SELECT p.*, c.nom_categorie AS famille_desc, m.description AS marque_desc 
                     FROM produits p 
                     JOIN categories c ON p.id_categorie = c.id_categorie 
                     JOIN marque m ON p.id_marque = m.id_marque 
                     WHERE p.id_marque = :id_marque";
            $params = array(':id_marque' => $_GET['id_marque']);
            $result = metodGet($query, $params);
            $data = $result->fetchAll(PDO::FETCH_ASSOC);

            http_response_code(200);
            echo json_encode($data);
            exit();
        }

        // Case 5: Search functionality
        if (isset($_GET['search'])) {
            $searchTerm = '%' . $_GET['search'] . '%';
            $query = "SELECT p.*, c.nom_categorie AS famille_desc, m.description AS marque_desc 
                     FROM produits p 
                     JOIN categories c ON p.id_categorie = c.id_categorie 
                     JOIN marque m ON p.id_marque = m.id_marque 
                     WHERE p.designation LIKE :search 
                     OR p.reference LIKE :search 
                     OR p.description LIKE :search";
            $params = array(':search' => $searchTerm);
            $result = metodGet($query, $params);
            $data = $result->fetchAll(PDO::FETCH_ASSOC);

            http_response_code(200);
            echo json_encode($data);
            exit();
        }

        // Case 6: Get all products (with optional stock filter)
        $query = "SELECT p.*, c.nom_categorie AS famille_desc, m.description AS marque_desc 
                 FROM produits p 
                 JOIN categories c ON p.id_categorie = c.id_categorie 
                 JOIN marque m ON p.id_marque = m.id_marque";

        // Add stock filter if specified
        if (isset($_GET['stock_filter'])) {
    switch ($_GET['stock_filter']) {
        case 'low':
            $query .= " WHERE p.stock_actuel <= p.stock_minimum AND p.stock_actuel > 0";
            break;
        case 'out':
            $query .= " WHERE p.stock_actuel = 0";
            break;
        case 'available':
            $query .= " WHERE p.stock_actuel > p.stock_minimum";
            break;
    }
}

        // Add sorting if specified
        if (isset($_GET['sort'])) {
            $sortField = in_array($_GET['sort'], ['designation', 'stock_actuel', 'prix_vente']) 
                        ? $_GET['sort'] : 'designation';
            $sortOrder = isset($_GET['order']) && strtoupper($_GET['order']) === 'DESC' ? 'DESC' : 'ASC';
            $query .= " ORDER BY p.$sortField $sortOrder";
        } else {
            $query .= " ORDER BY p.designation ASC";
        }

        $result = metodGet($query);
        $data = $result->fetchAll(PDO::FETCH_ASSOC);

        // Add warning for low stock items
        foreach ($data as &$product) {
            if ($product['stock_actuel'] <= $product['stock_minimum']) {
                $product['stock_warning'] = true;
            }
        }

        http_response_code(200);
        echo json_encode($data);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'status' => 'error',
            'message' => $e->getMessage(),
            'code' => 'SERVER_ERROR'
        ]);
    }
    exit();
}

if ($_POST['METHOD'] == 'POST') {
    requirePermission('article', 'add');

    unset($_POST['METHOD']);
    
    try {
        $categorie_code = $_POST['categorie_code'];
        $reference = reference_generator($categorie_code);
        
        $query = "INSERT INTO produits(
                    id_categorie, categorie_code, reference, unite, 
                    tva, designation, description, id_marque,
                    prix_achat, prix_vente, stock_minimum, stock_actuel,
                    garantie, user_cre
                  ) VALUES (
                    :id_categorie, :categorie_code, :reference, :unite,
                    :tva, :designation, :description, :id_marque,
                    :prix_achat, :prix_vente, :stock_minimum, :stock_actuel,
                    :garantie, :user_cre
                  )";
        
        $queryAutoIncrement = "SELECT MAX(id_produit) as id_produit FROM produits";
        
        $params = array(
            ':id_categorie' => $_POST['id_categorie'],
            ':categorie_code' => $categorie_code,
            ':reference' => $reference,
            ':unite' => $_POST['unite'],
            ':tva' => $_POST['tva'],
            ':designation' => $_POST['designation'],
            ':description' => $_POST['description'],
            ':id_marque' => $_POST['id_marque'],
            ':prix_achat' => $_POST['prix_achat'],
            ':prix_vente' => $_POST['prix_vente'],
            ':stock_minimum' => $_POST['stock_minimum'],
            ':stock_actuel' => $_POST['stock_actuel'],
            ':garantie' => $_POST['garantie'],
            ':user_cre' => $_POST['user_cre']
        );
        
        $result = metodPost($query, $queryAutoIncrement, $params, 'produits');
        echo json_encode($result);
        http_response_code(200);
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit();
}

if ($_POST['METHOD'] == 'PUT') {
    requirePermission('article', 'edit');

    unset($_POST['METHOD']);
    $id_produit = $_GET['id_produit'];
    
    $query = "UPDATE produits SET 
                id_categorie = :id_categorie,
                categorie_code = :categorie_code,
                unite = :unite,
                tva = :tva,
                designation = :designation,
                description = :description,
                id_marque = :id_marque,
                prix_achat = :prix_achat,
                prix_vente = :prix_vente,
                stock_minimum = :stock_minimum,
                stock_actuel = :stock_actuel,
                garantie = :garantie,
                user_upd = :user_upd
              WHERE id_produit = :id_produit";
    
    $params = array(
        ':id_produit' => $id_produit,
        ':id_categorie' => $_POST['id_categorie'],
        ':categorie_code' => $_POST['categorie_code'],
        ':unite' => $_POST['unite'],
        ':tva' => $_POST['tva'],
        ':designation' => $_POST['designation'],
        ':description' => $_POST['description'],
        ':id_marque' => $_POST['id_marque'],
        ':prix_achat' => $_POST['prix_achat'],
        ':prix_vente' => $_POST['prix_vente'],
        ':stock_minimum' => $_POST['stock_minimum'],
        ':stock_actuel' => $_POST['stock_actuel'],
        ':garantie' => $_POST['garantie'],
        ':user_upd' => $_POST['user_upd']
    );
    
    $result = metodPut($query, $params, 'produits');
    echo json_encode($result);
    http_response_code(200);
    exit();
}

if ($_POST['METHOD'] == 'DELETE') {
    requirePermission('article', 'delete');

    unset($_POST['METHOD']);
    $id = $_GET['id_produit'];
    $query = "DELETE FROM produits WHERE id_produit = :id";
    $params = array(':id' => $id);
    $result = metodDelete($query, $params, 'produits');
    echo json_encode($result);
    http_response_code(200);
    exit();
}

http_response_code(400);
?>
