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


if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Max-Age: 86400');
    http_response_code(204);
    exit();
}

requireAuth();

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    try {
        if (isset($_GET['id_vente'])) {
            $query = "SELECT * FROM ventes WHERE id_vente = :id_vente";
            $params = array(':id_vente' => $_GET['id_vente']);
            $result = metodGet($query, $params);
            echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
        } else {
            $query = "SELECT v.*, c.nom as client_nom FROM ventes v 
                     LEFT JOIN client c ON v.id_client = c.id_client
                     WHERE 1=1";
            $params = array();

            if (isset($_GET['id_client']) && $_GET['id_client'] !== '') {
                $query .= " AND v.id_client = :id_client";
                $params[':id_client'] = $_GET['id_client'];
            }

            if (isset($_GET['date_debut']) && $_GET['date_debut'] !== '') {
                $query .= " AND v.date_vente >= :date_debut";
                $params[':date_debut'] = $_GET['date_debut'];
            }
            if (isset($_GET['date_fin']) && $_GET['date_fin'] !== '') {
                $query .= " AND v.date_vente <= :date_fin";
                $params[':date_fin'] = $_GET['date_fin'];
            }
            if (isset($_GET['statut_paiement']) && $_GET['statut_paiement'] !== '') {
                $query .= " AND v.statut_paiement = :statut_paiement";
                $params[':statut_paiement'] = $_GET['statut_paiement'];
            }
            $query .= " ORDER BY v.date_vente DESC";

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

if ($_POST['METHOD'] == 'POST') {
    unset($_POST['METHOD']);

    try {
        $numero_vente = reference_generator($_POST['categorie_code']);

        $query = "INSERT INTO ventes(
                    id_client, categorie_code, numero_vente, date_vente,
                    montant_total, type_paiement, statut_paiement, commentaire,
                    user_cre
                  ) VALUES (
                    :id_client, :categorie_code, :numero_vente, :date_vente,
                    :montant_total, :type_paiement, :statut_paiement, :commentaire,
                    :user_cre
                  )";

        $queryAutoIncrement = "SELECT MAX(id_vente) as id_vente FROM ventes";

        $params = array(
            ':id_client' => $_POST['id_client'],
            ':categorie_code' => $_POST['categorie_code'],
            ':numero_vente' => $numero_vente,
            ':date_vente' => $_POST['date_vente'],
            ':montant_total' => $_POST['montant_total'],
            ':type_paiement' => $_POST['type_paiement'],
            ':statut_paiement' => $_POST['statut_paiement'],
            ':commentaire' => $_POST['commentaire'],
            ':user_cre' => $_POST['user_cre']
        );

        $result = metodPost($query, $queryAutoIncrement, $params, 'ventes');
        echo json_encode($result);
        header("HTTP/1.1 200 OK");
    } catch (Exception $e) {
        header("HTTP/1.1 500 Internal Server Error");
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit();
}

if ($_POST['METHOD'] == 'PUT') {
    unset($_POST['METHOD']);
    $id_vente = $_GET['id_vente'];

    try {
        $query = "UPDATE ventes SET
                    id_client = :id_client,
                    categorie_code = :categorie_code,
                    numero_vente = :numero_vente,
                    date_vente = :date_vente,
                    montant_total = :montant_total,
                    type_paiement = :type_paiement,
                    statut_paiement = :statut_paiement,
                    commentaire = :commentaire,
                    user_upd = :user_upd
                  WHERE id_vente = :id_vente";

        $params = array(
            ':id_vente' => $id_vente,
            ':id_client' => $_POST['id_client'],
            ':categorie_code' => $_POST['categorie_code'],
            ':numero_vente' => $_POST['numero_vente'],
            ':date_vente' => $_POST['date_vente'],
            ':montant_total' => $_POST['montant_total'],
            ':type_paiement' => $_POST['type_paiement'],
            ':statut_paiement' => $_POST['statut_paiement'],
            ':commentaire' => $_POST['commentaire'],
            ':user_upd' => $_POST['user_upd']
        );

        $result = metodPut($query, $params, 'ventes');
        
        // Always set JSON content type
        header('Content-Type: application/json');
        
        // Return a proper JSON response
        echo json_encode([
            'success' => true,
            'message' => 'Sale updated successfully',
            'data' => $result
        ]);
        
        header("HTTP/1.1 200 OK");
    } catch (Exception $e) {
        header("HTTP/1.1 500 Internal Server Error");
        header('Content-Type: application/json');
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit();
}

// In ventes.php, modify the DELETE section:


    // In ventes.php - Simplified DELETE section with debugging
    
    if ($_POST['METHOD'] === 'DELETE') {
        try {
            if (!isset($_GET['id_vente'])) {
                http_response_code(400);
                echo json_encode(['error' => 'id_vente parameter is required']);
                exit();
            }
    
            $id_vente = $_GET['id_vente'];
    
            // Check if sale exists
            $checkSaleQuery = "SELECT * FROM ventes WHERE id_vente = :id_vente";
            $params = array(':id_vente' => $id_vente);
            $result = metodGet($checkSaleQuery, $params);
            $sale = $result->fetch(PDO::FETCH_ASSOC);
    
            if (!$sale) {
                http_response_code(404);
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Sale not found'
                ]);
                exit();
            }
    
            // Check for payments
            $checkPaymentsQuery = "
                SELECT 
                    (SELECT COUNT(*) FROM paiements_clients_cash WHERE id_vente = :id_vente) +
                    (SELECT COUNT(*) FROM paiements_clients_tranches WHERE id_vente = :id_vente) as payment_count";
            $paymentResult = metodGet($checkPaymentsQuery, $params);
            $paymentCount = $paymentResult->fetch(PDO::FETCH_ASSOC)['payment_count'];
    
            if ($paymentCount > 0) {
                http_response_code(400);
                echo json_encode([
                    'status' => 'error',
                    'error' => 'Cannot delete sale',
                    'message' => 'This sale has associated payments and cannot be deleted.'
                ]);
                exit();
            }
    
            // Get sale details for stock update
            $getDetailsQuery = "SELECT id_produit, quantite FROM details_ventes WHERE id_vente = :id_vente";
            $detailsResult = metodGet($getDetailsQuery, $params);
            $details = $detailsResult->fetchAll(PDO::FETCH_ASSOC);
    
            // Update stock for each product
            foreach ($details as $detail) {
                $updateStockQuery = "UPDATE produits 
                                   SET stock_actuel = stock_actuel + :quantite 
                                   WHERE id_produit = :id_produit";
                $stockParams = array(
                    ':quantite' => $detail['quantite'],
                    ':id_produit' => $detail['id_produit']
                );
                $result = metodPut($updateStockQuery, $stockParams, 'produits');
            }
    
            // Delete sale details
            $deleteDetailsQuery = "DELETE FROM details_ventes WHERE id_vente = :id_vente";
            $result = metodDelete($deleteDetailsQuery, $params, 'details_ventes');
    
            // Delete sale
            $deleteSaleQuery = "DELETE FROM ventes WHERE id_vente = :id_vente";
            $result = metodDelete($deleteSaleQuery, $params, 'ventes');
    
            http_response_code(200);
            echo json_encode([
                'status' => 'success',
                'message' => 'Sale and its details have been successfully deleted'
            ]);
            exit();
    
        } catch (Exception $e) {
            error_log("Error in sale deletion: " . $e->getMessage());
            http_response_code(500);
            echo json_encode([
                'status' => 'error',
                'message' => 'An error occurred while deleting the sale: ' . $e->getMessage()
            ]);
            exit();
        }
    }

header("HTTP/1.1 400 Bad Request");
?>
