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

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


requireAuth();

function calculateMonthlyProfits($startDate, $endDate) {

    $query1 = "SELECT COALESCE(SUM(montant), 0) as total_paid_installments
               FROM reglements_tranches_clients 
               WHERE date_paiement IS NOT NULL 
               AND statut_reglements = 'Payé'
               AND date_paiement BETWEEN '$startDate' AND '$endDate'";
    

    $query2 = "SELECT COALESCE(SUM(montant_paye), 0) as total_cash_payments
               FROM paiements_clients_cash 
               WHERE date_paiement BETWEEN '$startDate' AND '$endDate'";
    
    $result1 = metodGet($query1)->fetch(PDO::FETCH_ASSOC);
    $result2 = metodGet($query2)->fetch(PDO::FETCH_ASSOC);
    
    return floatval($result1['total_paid_installments']) + floatval($result2['total_cash_payments']);
}

function calculateMonthlyLosses($startDate, $endDate) {

    $query1 = "SELECT COALESCE(SUM(montant), 0) as total_supplier_installments
               FROM reglements_tranches_fournisseurs 
               WHERE date_paiement IS NOT NULL 
               AND statut_reglements = 'Payé'
               AND date_paiement BETWEEN '$startDate' AND '$endDate'";
    

    $query2 = "SELECT COALESCE(SUM(montant_refund), 0) as total_refunds
               FROM refund_client 
               WHERE statut_refund = 'Remboursé'
               AND date_refund BETWEEN '$startDate' AND '$endDate'";
    

    $query3 = "SELECT COALESCE(SUM(montant_paye), 0) as total_supplier_cash
               FROM paiements_fournisseurs_cash
               WHERE date_paiement BETWEEN '$startDate' AND '$endDate'";
    
    $result1 = metodGet($query1)->fetch(PDO::FETCH_ASSOC);
    $result2 = metodGet($query2)->fetch(PDO::FETCH_ASSOC);
    $result3 = metodGet($query3)->fetch(PDO::FETCH_ASSOC);
    
    return floatval($result1['total_supplier_installments']) + 
           floatval($result2['total_refunds']) + 
           floatval($result3['total_supplier_cash']);
}

function calculatePeriodProfits($period = null) {
    if ($period) {
        $startDate = date('Y-m-d', strtotime("-$period days"));
        $endDate = date('Y-m-d');
        return calculateMonthlyProfits($startDate, $endDate);
    }
    

    $query1 = "SELECT COALESCE(SUM(montant), 0) as total_paid_installments
               FROM reglements_tranches_clients 
               WHERE date_paiement IS NOT NULL 
               AND statut_reglements = 'Payé'";
    
    $query2 = "SELECT COALESCE(SUM(montant_paye), 0) as total_cash_payments
               FROM paiements_clients_cash";
    
    $result1 = metodGet($query1)->fetch(PDO::FETCH_ASSOC);
    $result2 = metodGet($query2)->fetch(PDO::FETCH_ASSOC);
    
    return floatval($result1['total_paid_installments']) + floatval($result2['total_cash_payments']);
}

function calculatePeriodLosses($period = null) {
    if ($period) {
        $startDate = date('Y-m-d', strtotime("-$period days"));
        $endDate = date('Y-m-d');
        return calculateMonthlyLosses($startDate, $endDate);
    }
    

    $query1 = "SELECT COALESCE(SUM(montant), 0) as total_supplier_installments
               FROM reglements_tranches_fournisseurs 
               WHERE date_paiement IS NOT NULL 
               AND statut_reglements = 'Payé'";
    
    $query2 = "SELECT COALESCE(SUM(montant_refund), 0) as total_refunds
               FROM refund_client 
               WHERE statut_refund = 'Remboursé'";
    
    $query3 = "SELECT COALESCE(SUM(montant_paye), 0) as total_supplier_cash
               FROM paiements_fournisseurs_cash";
    
    $result1 = metodGet($query1)->fetch(PDO::FETCH_ASSOC);
    $result2 = metodGet($query2)->fetch(PDO::FETCH_ASSOC);
    $result3 = metodGet($query3)->fetch(PDO::FETCH_ASSOC);
    
    return floatval($result1['total_supplier_installments']) + 
           floatval($result2['total_refunds']) + 
           floatval($result3['total_supplier_cash']);
}

function calculateCustomerDebts() {
    $query = "SELECT COALESCE(SUM(montant), 0) as total_pending
              FROM reglements_tranches_clients 
              WHERE date_paiement IS NULL 
              AND statut_reglements = 'En attente'";
    
    $result = metodGet($query)->fetch(PDO::FETCH_ASSOC);
    return floatval($result['total_pending']);
}

function calculateOverdueAmounts() {
    $query = "SELECT COALESCE(SUM(montant), 0) as total_overdue
              FROM reglements_tranches_clients 
              WHERE date_paiement IS NULL 
              AND statut_reglements = 'En attente'
              AND date_echeance < CURRENT_DATE";
    
    $result = metodGet($query)->fetch(PDO::FETCH_ASSOC);
    return floatval($result['total_overdue']);
}

function calculateMonthlyTrends($year = null) {
    $trends = [];
    

    if (!$year) {
        $year = date('Y');
    }
    
    // Get all months for the specified year
    for ($month = 1; $month <= 12; $month++) {
        $startDate = sprintf('%d-%02d-01', $year, $month);
        $endDate = date('Y-m-t', strtotime($startDate));
        
        $monthlyProfits = calculateMonthlyProfits($startDate, $endDate);
        $monthlyLosses = calculateMonthlyLosses($startDate, $endDate);
        
        $trends[] = [
            'month' => date('F', strtotime($startDate)),
            'profits' => $monthlyProfits,
            'losses' => $monthlyLosses
        ];
    }
    
    return $trends;
}

function getSalesByProduct($startDate, $endDate) {
    $query = "SELECT p.designation as nom_produit, 
                     COUNT(dv.id_detail_vente) as nombre_ventes,
                     SUM(dv.quantite) as quantite_totale,
                     SUM(dv.montant_total) as montant_total
              FROM details_ventes dv
              JOIN produits p ON dv.id_produit = p.id_produit
              JOIN ventes v ON dv.id_vente = v.id_vente
              WHERE v.date_vente BETWEEN '$startDate' AND '$endDate'
              GROUP BY p.id_produit, p.designation
              ORDER BY montant_total DESC
              LIMIT 10";
              
    $result = metodGet($query);
    return $result->fetchAll(PDO::FETCH_ASSOC);
}


if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $type = isset($_GET['type']) ? $_GET['type'] : 'all';
        $response = [];

        if ($type === 'stats' || $type === 'all') {

            $startDate = isset($_GET['startDate']) ? $_GET['startDate'] : null;
            $endDate = isset($_GET['endDate']) ? $_GET['endDate'] : null;


            if (!$startDate || !$endDate) {
                $startDate = date('Y-m-01'); 
                $endDate = date('Y-m-t');    
            }

            $response = array_merge($response, [
                'profits' => calculateMonthlyProfits($startDate, $endDate),
                'losses' => calculateMonthlyLosses($startDate, $endDate),
                'customer_debts' => calculateCustomerDebts(),
                'overdue_amounts' => calculateOverdueAmounts(),
            ]);
        }

        if ($type === 'charts' || $type === 'all') {

            $year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');
            
            $response = array_merge($response, [
                'monthly_trends' => calculateMonthlyTrends($year),
                'top_products' => getSalesByProduct(
                    sprintf('%d-01-01', $year),
                    sprintf('%d-12-31', $year)
                ),
            ]);
        }
        
        echo json_encode($response);
        http_response_code(200);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit();
}


http_response_code(400);
?>