<?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('mouvement', 'view');
    try {
        $productId = isset($_GET['product_id']) ? $_GET['product_id'] : null;
        
        $baseQuery = "SELECT * FROM (
            SELECT 
                'Achat' as type_mouvement,
                da.quantite,
                a.date_achat as date_operation,
                'Achat' as source_mouvement,
                a.commentaire,
                p.designation,
                p.description,
                p.id_produit,
                da.prix_achat_unitaire as prix_unitaire,
                da.montant_total,
                f.raison_sociale as tiers
            FROM details_achats da
            JOIN achats a ON da.id_achat = a.id_achat
            JOIN produits p ON da.id_produit = p.id_produit
            JOIN fournisseur f ON a.id_fournisseur = f.id_fournisseur

            UNION ALL

            SELECT 
                'Vente' as type_mouvement,
                -dv.quantite as quantite,
                v.date_vente as date_operation,
                'Vente' as source_mouvement,
                v.commentaire,
                p.designation,
                p.description,
                p.id_produit,
                dv.prix_vente_unitaire as prix_unitaire,
                dv.montant_total,
                CONCAT(c.nom, ' ', c.prenom) as tiers
            FROM details_ventes dv
            JOIN ventes v ON dv.id_vente = v.id_vente
            JOIN produits p ON dv.id_produit = p.id_produit
            JOIN client c ON v.id_client = c.id_client
        ) as combined_movements";

        if ($productId) {
            $baseQuery .= " WHERE id_produit = :product_id";
        }

        $baseQuery .= " ORDER BY date_operation DESC LIMIT 20";

        $result = null;
        if ($productId) {
            $result = metodGet($baseQuery, array(':product_id' => $productId));
        } else {
            $result = metodGet($baseQuery);
        }

        $data = $result->fetchAll(PDO::FETCH_ASSOC);
        
        http_response_code(200);
        echo json_encode($data);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit();
}

http_response_code(400);
?>