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

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

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

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    if (isset($_GET['id_facture'])) {
        $query = "SELECT df.*,p.id_produit, p.designation 
                 FROM details_factures df
                 LEFT JOIN produits p ON df.id_produit = p.id_produit
                 WHERE df.id_facture = :id_facture";
        $params = array(':id_facture' => $_GET['id_facture']);
        $result = metodGet($query, $params);
        $data = $result->fetchAll(PDO::FETCH_ASSOC);
        http_response_code(200);
        echo json_encode($data);
        exit();
    } else {
        $query = "SELECT * FROM details_factures";
        $result = metodGet($query);
        http_response_code(200);
        echo json_encode($result->fetchAll());
        exit();
    }
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $method = isset($_POST['METHOD']) ? $_POST['METHOD'] : 'POST';
    unset($_POST['METHOD']);
    
    try {
        switch($method) {
            case 'POST':
                $query = "INSERT INTO details_factures(
                            id_facture, id_produit, quantite, prix_facture_unitaire,
                            montant_total, user_cre
                         ) VALUES (
                            :id_facture, :id_produit, :quantite, :prix_facture_unitaire,
                            :montant_total, :user_cre
                         )";
                $queryAutoIncrement = "SELECT MAX(id_detail_facture) as id_detail_facture FROM details_factures";
                $montant_total = $_POST['quantite'] * $_POST['prix_facture_unitaire'];
                $params = array(
                    ':id_facture' => $_POST['id_facture'],
                    ':id_produit' => $_POST['id_produit'],
                    ':quantite' => $_POST['quantite'],
                    ':prix_facture_unitaire' => $_POST['prix_facture_unitaire'],
                    ':montant_total' => $montant_total,
                    ':user_cre' => $_POST['user_cre']
                );
                $result = metodPost($query, $queryAutoIncrement, $params, 'details_factures');
                updateFactureTotal($_POST['id_facture']);
                http_response_code(201);
                echo json_encode([
                    'success' => true,
                    'message' => 'Facture detail created successfully',
                    'data' => $result,
                    'stock_info' => [
                        'new_stock' => $stockResult['new_stock'],
                        'is_low_stock' => $stockResult['is_low_stock']
                    ]
                ]);
                break;
            case 'PUT':
                if (!isset($_GET['id_detail_facture'])) {
                    throw new Exception("Detail ID is required for update");
                }
                
                $getDetailQuery = "SELECT id_produit, quantite FROM details_factures WHERE id_detail_facture = :id_detail_facture";
                $detailResult = metodGet($getDetailQuery, array(':id_detail_facture' => $_GET['id_detail_facture']));
                $currentDetail = $detailResult->fetch(PDO::FETCH_ASSOC);
                
                if (!$currentDetail) {
                    throw new Exception("Facture detail not found");
                }
                
                $query = "UPDATE details_factures 
                         SET id_produit = :id_produit,
                             quantite = :quantite,
                             prix_facture_unitaire = :prix_facture_unitaire,
                             montant_total = :montant_total,
                             user_upd = :user_upd,
                             date_upd = CURRENT_TIMESTAMP
                         WHERE id_detail_facture = :id_detail_facture";
                
                $montant_total = $_POST['quantite'] * $_POST['prix_facture_unitaire'];
                
                $params = array(
                    ':id_detail_facture' => $_GET['id_detail_facture'],
                    ':id_produit' => $_POST['id_produit'],
                    ':quantite' => $_POST['quantite'],
                    ':prix_facture_unitaire' => $_POST['prix_facture_unitaire'],
                    ':montant_total' => $montant_total,
                    ':user_upd' => $_POST['user_cre'] 
                );
                
                $result = metodPut($query, $params, 'details_factures');
                updateFactureTotal($_POST['id_facture']);
                
                http_response_code(200);
                echo json_encode([
                    'success' => true,
                    'message' => 'Facture detail updated successfully',
                    'data' => $result
                ]);
                break;
            
            case 'DELETE':
                if (!isset($_GET['id_detail_facture'])) {
                    throw new Exception("Detail ID is required for deletion");
                }

                $id = $_GET['id_detail_facture'];
                
                // First get the detail information for updating stock
                $getDetailQuery = "SELECT id_facture, id_produit, quantite FROM details_factures WHERE id_detail_facture = :id_detail_facture";
                $detailResult = metodGet($getDetailQuery, array(':id_detail_facture' => $id));
                $detailData = $detailResult->fetch(PDO::FETCH_ASSOC);
                
                if (!$detailData) {
                    throw new Exception("Facture detail not found");
                }
                
                // Delete the detail
                $query = "DELETE FROM details_factures WHERE id_detail_facture = :id";
                $params = array(':id' => $id);
                $result = metodDelete($query, $params, 'details_factures');
                
                // Update facture total
                updateFactureTotal($detailData['id_facture']);
                
                http_response_code(200);
                echo json_encode([
                    'success' => true,
                    'message' => 'Facture detail deleted successfully'
                ]);
                break;
        }
        exit();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
        exit();
    }
}

// Helper function to update the total amount of the sale
function updateFactureTotal($id_facture) {
    try {
        $query = "UPDATE factures f 
                 SET montant_total = (
                     SELECT COALESCE(SUM(montant_total), 0)
                     FROM details_factures 
                     WHERE id_facture = :id_facture
                 )
                 WHERE f.id_facture = :id_facture";
        
        $params = array(':id_facture' => $id_facture);
        metodPut($query, $params, 'factures');
    } catch (Exception $e) {
        error_log("Error updating sale total: " . $e->getMessage());
        throw new Exception("Error updating sale total");
    }
}
