<?php
// Fichier : src/Services/VATValidator.php
// Version 2.3 - Correction de l'écriture de régularisation des acomptes

namespace ComptaFlowPro\Services;

defined('ABSPATH') || exit;

class VATValidator {
    
    /**
     * Valide une déclaration CA3 et génère les écritures comptables complètes
     */
    public static function validateCA3Declaration(array $period_data, bool $payment_made = false): bool {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfp_';
        $user_id = get_current_user_id();
        
        $net_amount = $period_data['totals']['net'];
        $from_date = $period_data['period']['from'];
        $to_date = $period_data['period']['to'];
        
        $period_label = self::generatePeriodLabel($from_date, $to_date);
        $date_today = date('Y-m-d');
        
        // Création de la transaction dans le Hub
        $transaction_id = self::createHubTransaction(
            'VAT_PAYMENT', 
            $net_amount, 
            "Solde TVA " . $period_label, 
            $date_today, 
            'DGFIP'
        );

        if ($transaction_id === 0 && abs($net_amount) > 0.01) {
            throw new \Exception('Impossible de créer la transaction dans le Hub pour la CA3.');
        }
        
        $tva_data = self::calculatePeriodVATBalances($from_date, $to_date, $user_id);
        
        if ($tva_data['tva_collectee'] > 0 || $tva_data['tva_deductible'] > 0) {
            self::createVATRegularizationEntries($tva_data, $period_label, $user_id, $date_today, $transaction_id);
        }
        
        $wpdb->insert($prefix . 'vat_validations', [
            'user_id' => $user_id,
            'declaration_type' => 'CA3',
            'period_from' => $from_date,
            'period_to' => $to_date,
            'validated_at' => current_time('mysql'),
            'validation_method' => 'COMPTAFLOW_AUTO',
            'transaction_id' => $transaction_id ?: null
        ]);
        
        return true;
    }
    
    /**
     * Valide une déclaration CA12 et génère les écritures comptables complètes
     */
    public static function validateCA12Declaration(array $year_data, float $advances_paid, bool $payment_made = false): bool {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfp_';
        $user_id = get_current_user_id();
        
        $solde = $year_data['totals']['balance'];
        $fiscal_year = $year_data['fiscal_year'];
        $date_today = date('Y-m-d');
        
        $period_label = "Année $fiscal_year";

        // Création de la transaction Hub pour le solde final
        $transaction_id = self::createHubTransaction(
            'VAT_PAYMENT',
            $solde,
            "Solde TVA CA12 $fiscal_year",
            $date_today,
            'DGFIP'
        );

        if ($transaction_id === 0 && abs($solde) > 0.01) {
            throw new \Exception('Impossible de créer la transaction dans le Hub pour la CA12.');
        }

        $from_date = "$fiscal_year-01-01";
        $to_date = "$fiscal_year-12-31";
        $tva_data = self::calculatePeriodVATBalances($from_date, $to_date, $user_id);
        
        if ($tva_data['tva_collectee'] > 0 || $tva_data['tva_deductible'] > 0) {
            self::createVATRegularizationEntries($tva_data, $period_label, $user_id, $date_today, $transaction_id);
        }
        
        if ($advances_paid > 0) {
            self::createAdvanceRegularizationEntries($advances_paid, $fiscal_year, $user_id, $date_today, $transaction_id);
        }
        
        if ($solde > 0) {
             // La dette est déjà constatée dans le 44551 par la régularisation
        } elseif ($solde < 0) {
            // Le crédit est déjà constaté dans le 44551, on le transfère en 44567
            self::createVATCreditEntries(abs($solde), "Solde CA12 $fiscal_year", $user_id, $date_today, $transaction_id);
        }
        
        $wpdb->insert($prefix . 'vat_validations', [
            'user_id' => $user_id,
            'declaration_type' => 'CA12',
            'period_from' => "$fiscal_year-01-01",
            'period_to' => "$fiscal_year-12-31",
            'validated_at' => current_time('mysql'),
            'validation_method' => 'COMPTAFLOW_AUTO',
            'transaction_id' => $transaction_id ?: null
        ]);
        
        return true;
    }
    
    private static function createHubTransaction(string $type, float $amount, string $label, string $date, string $partner): int {
        if (abs($amount) < 0.01) { return 0; }
        global $wpdb;
        $hub_table = $wpdb->prefix . 'cfp_transactions';
        $data = [
            'uuid' => wp_generate_uuid4(),
            'type' => ($amount >= 0) ? 'VAT_PAYMENT' : 'VAT_REFUND',
            'date_txn' => $date,
            'label' => $label,
            'amount_ttc' => abs($amount),
            'amount_ht' => 0,
            'amount_tva' => 0,
            'payment_status' => 'PENDING',
            'partner_name' => $partner,
            'journal_code' => 'OD',
            'status' => 'POSTED',
            'created_by' => get_current_user_id(),
            'created_at' => current_time('mysql'),
        ];
        $result = $wpdb->insert($hub_table, $data);
        return ($result) ? $wpdb->insert_id : 0;
    }

    private static function createVATRegularizationEntries(array $tva_data, string $period_label, int $user_id, string $date_today, ?int $transaction_id): void {
        global $wpdb; $prefix = $wpdb->prefix . 'cfp_';
        $base_data = ['transaction_id' => $transaction_id, 'date_ecriture' => $date_today, 'journal_code' => 'OD', 'created_by' => $user_id, 'source' => 'VAT_DECLARATION'];
        if ($tva_data['tva_collectee'] > 0) {
            $wpdb->insert($prefix . 'journal_entries', array_merge($base_data, [ 'uuid' => wp_generate_uuid4(), 'compte_num' => '44571', 'libelle' => "Solde TVA collectée $period_label", 'debit' => $tva_data['tva_collectee'], 'credit' => 0 ]));
        }
        if ($tva_data['tva_deductible'] > 0) {
            $wpdb->insert($prefix . 'journal_entries', array_merge($base_data, [ 'uuid' => wp_generate_uuid4(), 'compte_num' => '44566', 'libelle' => "Solde TVA déductible $period_label", 'debit' => 0, 'credit' => $tva_data['tva_deductible'] ]));
        }
        if (abs($tva_data['net']) > 0.01) {
            if ($tva_data['net'] > 0) {
                $wpdb->insert($prefix . 'journal_entries', array_merge($base_data, [ 'uuid' => wp_generate_uuid4(), 'compte_num' => '44551', 'libelle' => "TVA due déclaration $period_label", 'debit' => 0, 'credit' => $tva_data['net'] ]));
            } else {
                $wpdb->insert($prefix . 'journal_entries', array_merge($base_data, [ 'uuid' => wp_generate_uuid4(), 'compte_num' => '44551', 'libelle' => "Crédit TVA déclaration $period_label", 'debit' => abs($tva_data['net']), 'credit' => 0 ]));
            }
        }
    }
    
    private static function createVATPaymentEntries(float $amount, string $period_label, bool $payment_made, int $user_id, string $date_today, ?int $transaction_id): void {
        // Cette fonction n'est plus utilisée pour créer la dette, seulement pour un paiement immédiat (obsolète)
    }

    private static function createVATCreditEntries(float $amount, string $period_label, int $user_id, string $date_today, ?int $transaction_id): void {
        global $wpdb; $prefix = $wpdb->prefix . 'cfp_';
        $base_data = ['transaction_id' => $transaction_id, 'date_ecriture' => $date_today, 'journal_code' => 'OD', 'created_by' => $user_id, 'source' => 'VAT_DECLARATION'];
        $wpdb->insert($prefix . 'journal_entries', array_merge($base_data, ['uuid' => wp_generate_uuid4(), 'compte_num' => '44567', 'libelle' => "Crédit TVA $period_label", 'debit' => $amount, 'credit' => 0]));
        $wpdb->insert($prefix . 'journal_entries', array_merge($base_data, ['uuid' => wp_generate_uuid4(), 'compte_num' => '44551', 'libelle' => "Solde créditeur $period_label", 'debit' => 0, 'credit' => $amount]));
    }
    
    // --- FONCTION CORRIGÉE ---
    private static function createAdvanceRegularizationEntries(float $advances_amount, int $fiscal_year, int $user_id, string $date_today, ?int $transaction_id): void {
        global $wpdb; 
        $prefix = $wpdb->prefix . 'cfp_';
        $base_data = [
            'transaction_id' => $transaction_id, 
            'date_ecriture' => $date_today, 
            'journal_code' => 'OD', 
            'created_by' => $user_id, 
            'source' => 'VAT_DECLARATION'
        ];
        
        // Débit 44551 / Crédit 44581
        // On débite le compte de TVA à décaisser du montant des acomptes déjà payés
        $wpdb->insert($prefix . 'journal_entries', array_merge($base_data, [
            'uuid' => wp_generate_uuid4(), 
            'compte_num' => '44551', 
            'libelle' => "Imputation acomptes TVA $fiscal_year", 
            'debit' => $advances_amount, 
            'credit' => 0
        ]));
        
        // On crédite le compte d'acomptes pour le solder (le remettre à zéro)
        $wpdb->insert($prefix . 'journal_entries', array_merge($base_data, [
            'uuid' => wp_generate_uuid4(), 
            'compte_num' => '44581', 
            'libelle' => "Solde acomptes TVA versés $fiscal_year", 
            'debit' => 0, 
            'credit' => $advances_amount
        ]));
    }
    // --- FIN DE LA FONCTION CORRIGÉE ---

    private static function calculatePeriodVATBalances(string $from_date, string $to_date, int $user_id): array {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfp_';
        $tva_collectee = $wpdb->get_var($wpdb->prepare( "SELECT COALESCE(SUM(amount_tva), 0) FROM {$prefix}transactions WHERE type = 'SALE' AND created_by = %d AND date_txn BETWEEN %s AND %s", $user_id, $from_date, $to_date ));
        $tva_deductible = $wpdb->get_var($wpdb->prepare( "SELECT COALESCE(SUM(amount_tva), 0) FROM {$prefix}transactions WHERE type = 'EXPENSE' AND created_by = %d AND date_txn BETWEEN %s AND %s", $user_id, $from_date, $to_date ));
        return [ 'tva_collectee' => floatval($tva_collectee), 'tva_deductible' => floatval($tva_deductible), 'net' => floatval($tva_collectee) - floatval($tva_deductible) ];
    }
    
    private static function generatePeriodLabel(string $from, string $to): string {
        $from_parts = explode('-', $from); $to_parts = explode('-', $to);
        $from_year = $from_parts[0]; $from_month = intval($from_parts[1]);
        $to_year = $to_parts[0]; $to_month = intval($to_parts[1]);
        $months = [ 1 => 'Janvier', 2 => 'Février', 3 => 'Mars', 4 => 'Avril', 5 => 'Mai', 6 => 'Juin', 7 => 'Juillet', 8 => 'Août', 9 => 'Septembre', 10 => 'Octobre', 11 => 'Novembre', 12 => 'Décembre' ];
        if ($from_year === $to_year && $from_month === $to_month) { return $months[$from_month] . ' ' . $from_year; }
        return $months[$from_month] . ' - ' . $months[$to_month] . ' ' . $to_year;
    }
    
    public static function isPeriodValidated(string $declaration_type, string $from, string $to, int $user_id = 0): bool {
        global $wpdb; $prefix = $wpdb->prefix . 'cfp_'; $uid = $user_id ?: get_current_user_id();
        $count = $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM {$prefix}vat_validations WHERE user_id = %d AND declaration_type = %s AND period_from = %s AND period_to = %s", $uid, $declaration_type, $from, $to ));
        return intval($count) > 0;
    }
    
    public static function getValidationHistory(int $user_id = 0): array {
        global $wpdb; $prefix = $wpdb->prefix . 'cfp_'; $uid = $user_id ?: get_current_user_id();
        return $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$prefix}vat_validations WHERE user_id = %d ORDER BY validated_at DESC LIMIT 50", $uid ), ARRAY_A);
    }
}