<?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_facture'])) {
            $query = "SELECT * FROM factures WHERE id_facture = :id_facture";
            $params = array(':id_facture' => $_GET['id_facture']);
            $result = metodGet($query, $params);
            echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
        } else {
            $query = "SELECT v.*, c.nom as client_nom FROM factures 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_facture >= :date_debut";
                $params[':date_debut'] = $_GET['date_debut'];
            }
            if (isset($_GET['date_fin']) && $_GET['date_fin'] !== '') {
                $query .= " AND v.date_facture <= :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_facture 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_facture = reference_generator($_POST['categorie_code']);

        $query = "INSERT INTO factures(
                    id_client, categorie_code, numero_facture, date_facture,
                    montant_total, type_paiement, statut_paiement, commentaire,
                    user_cre
                  ) VALUES (
                    :id_client, :categorie_code, :numero_facture, :date_facture,
                    :montant_total, :type_paiement, :statut_paiement, :commentaire,
                    :user_cre
                  )";

        $queryAutoIncrement = "SELECT MAX(id_facture) as id_facture FROM factures";

        $params = array(
            ':id_client' => $_POST['id_client'],
            ':categorie_code' => $_POST['categorie_code'],
            ':numero_facture' => $numero_facture,
            ':date_facture' => $_POST['date_facture'],
            ':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, 'factures');
        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_facture = $_GET['id_facture'];

    try {
        $query = "UPDATE factures SET
                    id_client = :id_client,
                    categorie_code = :categorie_code,
                    numero_facture = :numero_facture,
                    date_facture = :date_facture,
                    montant_total = :montant_total,
                    type_paiement = :type_paiement,
                    statut_paiement = :statut_paiement,
                    commentaire = :commentaire,
                    user_upd = :user_upd
                  WHERE id_facture = :id_facture";

        $params = array(
            ':id_facture' => $id_facture,
            ':id_client' => $_POST['id_client'],
            ':categorie_code' => $_POST['categorie_code'],
            ':numero_facture' => $_POST['numero_facture'],
            ':date_facture' => $_POST['date_facture'],
            ':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, 'factures');
        
        // Always set JSON content type
        header('Content-Type: application/json');
        
        // Return a proper JSON response
        echo json_encode([
            'success' => true,
            'message' => 'Facture 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();
}

if ($_POST['METHOD'] == 'DELETE') {
    unset($_POST['METHOD']);
    $id = $_GET['id_facture'];

    try {
        // First delete all associated details
        $deleteDetailsQuery = "DELETE FROM details_factures WHERE id_facture = :id";
        $params = array(':id' => $id);
        metodDelete($deleteDetailsQuery, $params, 'details_factures');

        // Then delete the facture
        $deleteFactureQuery = "DELETE FROM factures WHERE id_facture = :id";
        $result = metodDelete($deleteFactureQuery, $params, 'factures');

        echo json_encode([
            'success' => true,
            'message' => 'Facture and all associated details deleted successfully',
            'data' => $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();
}

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