<?php
// Fichier : src/Services/VATCalculator.php
// Version 2.0 - Service de calculs TVA pour CA3 mensuel/trimestriel

namespace ComptaFlowPro\Services;

defined('ABSPATH') || exit;

class VATCalculator {
    
    /**
     * Calcule les totaux TVA pour une période donnée (pour CA3)
     */
    public static function totals(string $from, string $to, int $user_id = 0): array {
        $uid = $user_id ?: get_current_user_id();
        
        // Récupération des données brutes
        $raw_data = self::getRawVATData($from, $to, $uid);
        
        // Calculs par taux
        $by_rate = self::calculateByRate($raw_data);
        
        // Totaux
        $totals = self::calculateTotals($by_rate);
        
        // Statistiques
        $stats = self::calculateStats($raw_data);
        
        return [
            'period' => ['from' => $from, 'to' => $to],
            'totals' => $totals,
            'by_rate' => $by_rate,
            'stats' => $stats
        ];
    }
    
    /**
     * Récupère les données brutes de transactions pour la période
     */
    private static function getRawVATData(string $from, string $to, int $user_id): array {
        global $wpdb;
        
        $results = $wpdb->get_results($wpdb->prepare("
            SELECT 
                type,
                amount_ht,
                amount_tva,
                amount_ttc,
                vat_rate,
                account_code,
                date_txn,
                label
            FROM {$wpdb->prefix}cfp_transactions 
            WHERE created_by = %d 
            AND date_txn BETWEEN %s AND %s 
            AND status = 'POSTED'
            AND type IN ('SALE', 'EXPENSE')
            ORDER BY date_txn ASC
        ", $user_id, $from, $to), ARRAY_A);
        
        return $results ?: [];
    }
    
    /**
     * Calcule les montants par taux de TVA
     */
    private static function calculateByRate(array $raw_data): array {
        $by_rate = [
            'collectee' => [],
            'deductible_achats' => [],
            'deductible_immob' => []
        ];
        
        foreach ($raw_data as $row) {
            $rate = number_format((float)$row['vat_rate'], 2);
            $amount_ht = (float)$row['amount_ht'];
            $amount_tva = (float)$row['amount_tva'];
            
            if ($row['type'] === 'SALE') {
                // TVA Collectée
                if (!isset($by_rate['collectee'][$rate])) {
                    $by_rate['collectee'][$rate] = [
                        'rate' => $rate,
                        'base_ht' => 0,
                        'tva_amount' => 0,
                        'count' => 0
                    ];
                }
                $by_rate['collectee'][$rate]['base_ht'] += $amount_ht;
                $by_rate['collectee'][$rate]['tva_amount'] += $amount_tva;
                $by_rate['collectee'][$rate]['count']++;
                
            } elseif ($row['type'] === 'EXPENSE') {
                // TVA Déductible - Déterminer si immobilisation ou achat
                $is_immob = self::isImmobilizationAccount($row['account_code']);
                $category = $is_immob ? 'deductible_immob' : 'deductible_achats';
                
                if (!isset($by_rate[$category][$rate])) {
                    $by_rate[$category][$rate] = [
                        'rate' => $rate,
                        'base_ht' => 0,
                        'tva_amount' => 0,
                        'count' => 0
                    ];
                }
                $by_rate[$category][$rate]['base_ht'] += $amount_ht;
                $by_rate[$category][$rate]['tva_amount'] += $amount_tva;
                $by_rate[$category][$rate]['count']++;
            }
        }
        
        return $by_rate;
    }
    
    /**
     * Détermine si un compte comptable correspond à une immobilisation
     */
    private static function isImmobilizationAccount(string $account_code): bool {
        // Comptes d'immobilisations (classe 2)
        $immob_patterns = [
            '2183', // Matériel informatique
            '2182', // Matériel de transport
            '2184', // Mobilier
            '2181', // Installations générales
            '213',  // Constructions (début)
            '215',  // Installations techniques (début)
        ];
        
        foreach ($immob_patterns as $pattern) {
            if (strpos($account_code, $pattern) === 0) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Calcule les totaux généraux
     */
    private static function calculateTotals(array $by_rate): array {
        $totals = [
            'collectee' => 0,
            'deductible_achats' => 0,
            'deductible_immob' => 0,
            'deductible' => 0,
            'net' => 0
        ];
        
        // TVA Collectée
        foreach ($by_rate['collectee'] as $rate_data) {
            $totals['collectee'] += $rate_data['tva_amount'];
        }
        
        // TVA Déductible achats
        foreach ($by_rate['deductible_achats'] as $rate_data) {
            $totals['deductible_achats'] += $rate_data['tva_amount'];
        }
        
        // TVA Déductible immobilisations
        foreach ($by_rate['deductible_immob'] as $rate_data) {
            $totals['deductible_immob'] += $rate_data['tva_amount'];
        }
        
        // Total déductible
        $totals['deductible'] = $totals['deductible_achats'] + $totals['deductible_immob'];
        
        // Solde net (positif = à payer, négatif = crédit)
        $totals['net'] = $totals['collectee'] - $totals['deductible'];
        
        return $totals;
    }
    
    /**
     * Calcule des statistiques complémentaires
     */
    private static function calculateStats(array $raw_data): array {
        $stats = [
            'total_transactions' => count($raw_data),
            'sales_count' => 0,
            'expenses_count' => 0,
            'total_ca_ht' => 0,
            'total_expenses_ht' => 0,
            'avg_transaction_amount' => 0
        ];
        
        $total_amount = 0;
        
        foreach ($raw_data as $row) {
            $amount_ht = (float)$row['amount_ht'];
            $total_amount += $amount_ht;
            
            if ($row['type'] === 'SALE') {
                $stats['sales_count']++;
                $stats['total_ca_ht'] += $amount_ht;
            } elseif ($row['type'] === 'EXPENSE') {
                $stats['expenses_count']++;
                $stats['total_expenses_ht'] += $amount_ht;
            }
        }
        
        if ($stats['total_transactions'] > 0) {
            $stats['avg_transaction_amount'] = $total_amount / $stats['total_transactions'];
        }
        
        return $stats;
    }
    
    /**
     * Formate les données pour l'affichage CA3
     */
    public static function formatForCA3Display(array $vat_data): array {
        return [
            // Lignes principales CA3
            'ligne_08' => $vat_data['by_rate']['collectee']['20.00'] ?? null,
            'ligne_09' => $vat_data['by_rate']['collectee']['5.50'] ?? null,
            'ligne_9B' => $vat_data['by_rate']['collectee']['10.00'] ?? null,
            
            // TVA déductible
            'ligne_20' => [
                'tva_deductible' => $vat_data['totals']['deductible_achats']
            ],
            'ligne_19' => [
                'tva_deductible' => $vat_data['totals']['deductible_immob']
            ],
            
            // Totaux pour CA3
            'total_tva_brute' => $vat_data['totals']['collectee'],
            'total_tva_deductible' => $vat_data['totals']['deductible'],
            'solde_net' => $vat_data['totals']['net']
        ];
    }
    
    /**
     * Vérifie si une période a déjà été déclarée
     */
    public static function isPeriodDeclared(string $from, string $to, int $user_id = 0): bool {
        global $wpdb;
        $uid = $user_id ?: get_current_user_id();
        
        $count = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) 
            FROM {$wpdb->prefix}cfp_vat_declarations 
            WHERE user_id = %d 
            AND declaration_type = 'CA3'
            AND period_start = %s 
            AND period_end = %s
        ", $uid, $from, $to));
        
        return $count > 0;
    }
    
    /**
     * Calcule la TVA pour une période spécifique (méthode utilitaire)
     */
    public static function calculatePeriodVAT(string $from, string $to, int $user_id = 0): array {
        return self::totals($from, $to, $user_id);
    }
    
    /**
     * Obtient les taux de TVA configurés
     */
    public static function getConfiguredVATRates(): array {
        return [
            '20.00' => 'Taux normal (20%)',
            '10.00' => 'Taux réduit (10%)', 
            '5.50' => 'Taux réduit (5,5%)',
            '2.10' => 'Taux particulier (2,1%)',
            '0.00' => 'Exonéré'
        ];
    }
}