<?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_achat'])) {
            $query = "SELECT * FROM achats WHERE id_achat = :id_achat";
            $params = array(':id_achat' => $_GET['id_achat']);
            $result = metodGet($query, $params);
            echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
        } else {
            $query = "SELECT a.*, f.raison_sociale as fournisseur_nom FROM achats a 
                     LEFT JOIN fournisseur f ON a.id_fournisseur = f.id_fournisseur
                     WHERE 1=1";
            $params = array();

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

            if (isset($_GET['date_debut']) && $_GET['date_debut'] !== '') {
                $query .= " AND a.date_achat >= :date_debut";
                $params[':date_debut'] = $_GET['date_debut'];
            }
            if (isset($_GET['date_fin']) && $_GET['date_fin'] !== '') {
                $query .= " AND a.date_achat <= :date_fin";
                $params[':date_fin'] = $_GET['date_fin'];
            }
            if (isset($_GET['statut_paiement']) && $_GET['statut_paiement'] !== '') {
                $query .= " AND a.statut_paiement = :statut_paiement";
                $params[':statut_paiement'] = $_GET['statut_paiement'];
            }
            $query .= " ORDER BY a.date_achat 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_achat = reference_generator($_POST['categorie_code']);

        $query = "INSERT INTO achats(
                    id_fournisseur, categorie_code, numero_achat, date_achat,
                    montant_total, type_paiement, statut_paiement, commentaire,
                    user_cre
                  ) VALUES (
                    :id_fournisseur, :categorie_code, :numero_achat, :date_achat,
                    :montant_total, :type_paiement, :statut_paiement, :commentaire,
                    :user_cre
                  )";

        $queryAutoIncrement = "SELECT MAX(id_achat) as id_achat FROM achats";

        $params = array(
            ':id_fournisseur' => $_POST['id_fournisseur'],
            ':categorie_code' => $_POST['categorie_code'],
            ':numero_achat' => $numero_achat,
            ':date_achat' => $_POST['date_achat'],
            ':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, 'achats');
        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_achat = $_GET['id_achat'];

    try {
        $query = "UPDATE achats SET
                    id_fournisseur = :id_fournisseur,
                    categorie_code = :categorie_code,
                    numero_achat = :numero_achat,
                    date_achat = :date_achat,
                    montant_total = :montant_total,
                    type_paiement = :type_paiement,
                    statut_paiement = :statut_paiement,
                    commentaire = :commentaire,
                    user_upd = :user_upd
                  WHERE id_achat = :id_achat";

        $params = array(
            ':id_achat' => $id_achat,
            ':id_fournisseur' => $_POST['id_fournisseur'],
            ':categorie_code' => $_POST['categorie_code'],
            ':numero_achat' => $_POST['numero_achat'],
            ':date_achat' => $_POST['date_achat'],
            ':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, 'achats');
        
        // Always set JSON content type
        header('Content-Type: application/json');
        
        // Return a proper JSON response
        echo json_encode([
            'success' => true,
            'message' => 'Purchase 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 achats.php, modify the DELETE section:


    // In achats.php - Simplified DELETE section with debugging
    
    if ($_POST['METHOD'] === 'DELETE') {
        try {
            if (!isset($_GET['id_achat'])) {
                http_response_code(400);
                echo json_encode(['error' => 'id_achat parameter is required']);
                exit();
            }
    
            $id_achat = $_GET['id_achat'];
    
            // Check if purchase exists
            $checkPurchaseQuery = "SELECT * FROM achats WHERE id_achat = :id_achat";
            $params = array(':id_achat' => $id_achat);
            $result = metodGet($checkPurchaseQuery, $params);
            $purchase = $result->fetch(PDO::FETCH_ASSOC);
    
            if (!$purchase) {
                http_response_code(404);
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Purchase not found'
                ]);
                exit();
            }
    
            // Check for payments
            $checkPaymentsQuery = "
                SELECT 
                    (SELECT COUNT(*) FROM paiements_fournisseurs_cash WHERE id_achat = :id_achat) +
                    (SELECT COUNT(*) FROM paiements_fournisseurs_tranches WHERE id_achat = :id_achat) 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 purchase',
                    'message' => 'This purchase has associated payments and cannot be deleted.'
                ]);
                exit();
            }
    
            // Get purchase details for stock update
            $getDetailsQuery = "SELECT id_produit, quantite FROM details_achats WHERE id_achat = :id_achat";
            $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 purchase details
            $deleteDetailsQuery = "DELETE FROM details_achats WHERE id_achat = :id_achat";
            $result = metodDelete($deleteDetailsQuery, $params, 'details_achats');
    
            // Delete purchase
            $deletePurchaseQuery = "DELETE FROM achats WHERE id_achat = :id_achat";
            $result = metodDelete($deletePurchaseQuery, $params, 'achats');
    
            http_response_code(200);
            echo json_encode([
                'status' => 'success',
                'message' => 'Purchase and its details have been successfully deleted'
            ]);
            exit();
    
        } catch (Exception $e) {
            error_log("Error in purchase deletion: " . $e->getMessage());
            http_response_code(500);
            echo json_encode([
                'status' => 'error',
                'message' => 'An error occurred while deleting the purchase: ' . $e->getMessage()
            ]);
            exit();
        }
    }

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