<?php
// client.php

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

// Protect all routes with authentication
requireAuth();

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    requirePermission('client', 'view');

    if (isset($_GET['id_client'])) {
        $query = "SELECT * FROM client WHERE id_client = :id_client";
        $params = array(':id_client' => $_GET['id_client']);
        $result = metodGet($query, $params);
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    } else if (isset($_GET['retard'])) {
        $query = "SELECT 
                    c.*,
                    (
                        SELECT MIN(rtc.date_echeance)
                        FROM ventes v
                        JOIN paiements_clients_tranches pct ON v.id_vente = pct.id_vente
                        JOIN reglements_tranches_clients rtc ON pct.id_paiement_tranche = rtc.id_paiement_tranche
                        WHERE v.id_client = c.id_client
                        AND (rtc.date_paiement IS NULL OR rtc.statut_reglements != 'Payé')
                    ) as date_echeance,
                    DATEDIFF(CURRENT_DATE, (
                        SELECT MIN(rtc.date_echeance)
                        FROM ventes v
                        JOIN paiements_clients_tranches pct ON v.id_vente = pct.id_vente
                        JOIN reglements_tranches_clients rtc ON pct.id_paiement_tranche = rtc.id_paiement_tranche
                        WHERE v.id_client = c.id_client
                        AND (rtc.date_paiement IS NULL OR rtc.statut_reglements != 'Payé')
                    )) as days_late
                FROM client c";
        
        $result = metodGet($query);
        echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
    } else {
        $query = "SELECT * FROM client";
        $result = metodGet($query);
        echo json_encode($result->fetchAll());
    }
    header("HTTP/1.1 200 OK");
    exit();
}

// client.php
if ($_POST['METHOD'] == 'POST') {
    requirePermission('client', 'add');
    
    try {
        // Log incoming data
        error_log("POST DATA: " . print_r($_POST, true));
        
        unset($_POST['METHOD']);
        
        // Validate categorie_code
        if (!isset($_POST['categorie_code']) || empty($_POST['categorie_code'])) {
            throw new Exception("categorie_code is required");
        }
        
        $categorie_code = intval($_POST['categorie_code']);
        
        // Check if categorie_code exists in bsgcod table
        $check_query = "SELECT Code FROM bsgcod WHERE Code = :code";
        $check_params = array(':code' => $categorie_code);
        $result = metodGet($check_query, $check_params)->fetch(PDO::FETCH_ASSOC);
        
        if (!$result) {
            throw new Exception("Invalid categorie_code: $categorie_code");
        }
        
        // Generate reference code
        try {
            $Code_Client = reference_generator($categorie_code);
            error_log("Generated Code_Client: " . $Code_Client);
        } catch (Exception $e) {
            error_log("Error in reference_generator: " . $e->getMessage());
            throw new Exception("Error generating reference code: " . $e->getMessage());
        }
        
        // Prepare insert query
        $query = "INSERT INTO client(
                    Code_Client, categorie_code, nom, prenom, adresse, 
                    telephone, email, cin, `grant`, description, 
                    profession, user_cre
                ) VALUES (
                    :Code_Client, :categorie_code, :nom, :prenom, :adresse,
                    :telephone, :email, :cin, :grant, :description,
                    :profession, :user_cre
                )";
        
        $queryAutoIncrement = "SELECT MAX(id_client) as id_client FROM client";
        
        $params = array(
            ':Code_Client' => $Code_Client,
            ':categorie_code' => $categorie_code,
            ':nom' => $_POST['nom'],
            ':prenom' => $_POST['prenom'],
            ':adresse' => $_POST['adresse'] ?? '',
            ':telephone' => $_POST['telephone'] ?? '',
            ':email' => $_POST['email'] ?? '',
            ':cin' => $_POST['cin'] ?? '',
            ':grant' => $_POST['grant'] ?? '',
            ':description' => $_POST['description'] ?? '',
            ':profession' => $_POST['profession'] ?? '',
            ':user_cre' => $_POST['user_cre']
        );
        
        error_log("Insert query params: " . print_r($params, true));
        
        $result = metodPost($query, $queryAutoIncrement, $params, 'client');
        
        header('Content-Type: application/json');
        echo json_encode($result);
        
    } catch (Exception $e) {
        error_log("Error in client creation: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
        
        header('Content-Type: application/json');
        http_response_code(500);
        echo json_encode([
            'error' => $e->getMessage(),
            'details' => 'Error occurred while creating client'
        ]);
    }
    exit();
}

if ($_POST['METHOD'] == 'PUT') {
    try {
        requirePermission('client', 'edit');

        // Log incoming data
        error_log("PUT request received");
        error_log("POST data: " . print_r($_POST, true));
        error_log("GET data: " . print_r($_GET, true));

        if (!isset($_GET['id_client'])) {
            throw new Exception("Client ID is required");
        }

        $id_client = $_GET['id_client'];

        // Validate required fields
        $required_fields = ['categorie_code', 'nom', 'prenom'];
        foreach ($required_fields as $field) {
            if (!isset($_POST[$field]) || empty($_POST[$field])) {
                throw new Exception("Missing required field: $field");
            }
        }

        // First check if client exists
        $check_query = "SELECT id_client FROM client WHERE id_client = :id_client";
        $check_result = metodGet($check_query, array(':id_client' => $id_client));
        if (!$check_result->fetch()) {
            throw new Exception("Client not found");
        }

        $query = "UPDATE client SET 
            categorie_code = :categorie_code,
            nom = :nom,
            prenom = :prenom,
            adresse = :adresse,
            telephone = :telephone,
            email = :email,
            cin = :cin,
            `grant` = :grant,
            description = :description,
            profession = :profession,
            user_upd = :user_upd,
            date_upd = CURRENT_TIMESTAMP
            WHERE id_client = :id_client";

        $params = array(
            ':id_client' => $id_client,
            ':categorie_code' => $_POST['categorie_code'],
            ':nom' => $_POST['nom'],
            ':prenom' => $_POST['prenom'],
            ':adresse' => $_POST['adresse'] ?? '',
            ':telephone' => $_POST['telephone'] ?? '',
            ':email' => $_POST['email'] ?? '',
            ':cin' => $_POST['cin'] ?? '',
            ':grant' => $_POST['grant'] ?? '',
            ':description' => $_POST['description'] ?? '',
            ':profession' => $_POST['profession'] ?? '',
            ':user_upd' => $_POST['user_upd']
        );

        // Log the query and parameters
        error_log("Update query: " . $query);
        error_log("Parameters: " . print_r($params, true));

        $result = metodPut($query, $params, 'client');

        if ($result) {
            echo json_encode([
                'success' => true,
                'message' => 'Client updated successfully'
            ]);
            header("HTTP/1.1 200 OK");
        } else {
            throw new Exception("Failed to update client");
        }
    } catch (Exception $e) {
        error_log("Error updating client: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
        
        http_response_code(400);
        echo json_encode([
            'error' => true,
            'message' => $e->getMessage(),
            'details' => 'Error occurred while updating client'
        ]);
    }
    exit();
}

// In client.php
if ($_POST['METHOD'] == 'DELETE') {
    try {
        requirePermission('client', 'delete');
        error_log("DELETE request received for client ID: " . $_GET['id_client']);

        if (!isset($_GET['id_client'])) {
            throw new Exception("Client ID is required");
        }
        
        $id_client = $_GET['id_client'];

        // Check for related records in ventes table
        $check_ventes = "SELECT COUNT(*) as count FROM ventes WHERE id_client = :id_client";
        $result = metodGet($check_ventes, array(':id_client' => $id_client));
        $count = $result->fetch(PDO::FETCH_ASSOC)['count'];
        
        if ($count > 0) {
            throw new Exception("Cannot delete client: Client has related sales records");
        }

        // Delete the client
        $query = "DELETE FROM client WHERE id_client = :id_client";
        $params = array(':id_client' => $id_client);
        
        error_log("Executing delete query with params: " . print_r($params, true));
        
        $result = metodDelete($query, $params, 'client');

        if ($result) {
            echo json_encode([
                'success' => true,
                'message' => 'Client deleted successfully'
            ]);
            header("HTTP/1.1 200 OK");
        } else {
            throw new Exception("Failed to delete client");
        }
    } catch (Exception $e) {
        error_log("Error deleting client: " . $e->getMessage());
        http_response_code(400);
        echo json_encode([
            'error' => true,
            'message' => $e->getMessage()
        ]);
    }
    exit();
}

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