<?php
namespace ComptaFlowPro;

use ComptaFlowPro\Services\DB;
use ComptaFlowPro\Admin\Menu;
use ComptaFlowPro\Admin\Screens\ClientsScreen;
use ComptaFlowPro\Admin\Screens\InvoicesScreen;
use ComptaFlowPro\Security\Capabilities;

defined('ABSPATH') || exit;

class Bootstrap {
    
    public static function init(): void {
        register_activation_hook(COMPTAFLOW_PLUGIN_FILE, [self::class, 'activate']);
        register_deactivation_hook(COMPTAFLOW_PLUGIN_FILE, [self::class, 'deactivate']);
        
        add_action('admin_menu', [Menu::class, 'register']);
        add_action('admin_init', [self::class, 'handleEarlyActions']);
        add_action('wp_dashboard_setup', [self::class, 'addDashboardWidget']);
        add_action('admin_enqueue_scripts', [self::class, 'enqueueAdminAssets']);
        
        \ComptaFlowPro\Services\ExportHandler::register();

        Capabilities::init();
    }
    
    /**
     * Traiter les redirections (POST/actions) AVANT l'output WordPress
     */
    public static function handleEarlyActions(): void {
        if (!current_user_can('manage_options')) {
            return;
        }

        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';

        if ($page === 'comptaflow-clients') {
            ClientsScreen::handleActions();
        }

        if ($page === 'comptaflow-invoices') {
            InvoicesScreen::handleActions();
        }
    }

    public static function activate(): void {
        DB::createTables();
        Capabilities::addCapabilities();
        
        flush_rewrite_rules();
    }
    
    public static function deactivate(): void {
        // Cleanup if necessary
    }
    
    /**
     * Add ComptaFlow widget to WordPress dashboard
     */
    public static function addDashboardWidget(): void {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        wp_add_dashboard_widget(
            'comptaflow_pro_widget',
            __('ComptaFlow - This Month\'s Tasks', 'comptaflow-by-meetempo'),
            [self::class, 'renderDashboardWidget']
        );
    }
    
    /**
     * Render dashboard widget content
     */
    public static function renderDashboardWidget(): void {
        $user_id = get_current_user_id();
        
        echo '<div style="padding: 15px;">';
        
        // Quick stats
        $stats = self::getQuickStats();
        
        echo '<div style="display: flex; justify-content: space-between; margin-bottom: 15px;">';
        echo '<div style="text-align: center;">';
        echo '<strong style="font-size: 18px; color: #0073aa;">' . esc_html(number_format($stats['ca_month'], 0)) . '€</strong><br>';
        echo '<small>' . esc_html__('Revenue this month', 'comptaflow-by-meetempo') . '</small>';
        echo '</div>';
        echo '<div style="text-align: center;">';
        $solde_tva = $stats['tva_collected'] - $stats['tva_deductible'];
        $color = $solde_tva >= 0 ? '#d63638' : '#00a32a';
        echo '<strong style="font-size: 18px; color: ' . esc_attr($color) . ';">' . esc_html(number_format(abs($solde_tva), 0)) . '€</strong><br>';
        echo '<small>' . esc_html($solde_tva >= 0 ? __('VAT to pay', 'comptaflow-by-meetempo') : __('VAT credit', 'comptaflow-by-meetempo')) . '</small>';
        echo '</div>';
        echo '</div>';
        
        // Pending transactions
        $pending_count = self::getPendingTransactions();
        if ($pending_count > 0) {
            echo '<div style="background: #e7f3ff; padding: 8px; margin-bottom: 10px; border-radius: 3px; border-left: 4px solid #0073aa;">';
            echo '<strong>' . sprintf(
                /* translators: %d: number of pending transactions */
                esc_html(_n('%d pending transaction', '%d pending transactions', $pending_count, 'comptaflow-by-meetempo')),
                $pending_count
            ) . '</strong><br>';
            echo '<small>' . esc_html__('Invoices awaiting collection or payment', 'comptaflow-by-meetempo') . '</small>';
            echo '</div>';
        }
        
        // Upsell for PRO
        echo '<div style="background: #f0f7ff; padding: 8px; margin-bottom: 10px; border-radius: 3px; font-size: 11px; text-align: center; border: 1px solid #c3d9ed;">';
        echo '<strong>' . esc_html__('Need more features?', 'comptaflow-by-meetempo') . '</strong><br>';
        echo '<small><a href="' . esc_url(admin_url('admin.php?page=comptaflow-plans')) . '">' . esc_html__('Discover ComptaFlow Pro: FEC export, VAT, Bank reconciliation...', 'comptaflow-by-meetempo') . '</a></small>';
        echo '</div>';
        
        // Quick actions
        echo '<div style="display: flex; gap: 6px; margin-top: 10px;">';
        echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-sales&action=new')) . '" class="button button-small">+ ' . esc_html__('Sale', 'comptaflow-by-meetempo') . '</a>';
        echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-expenses&action=new')) . '" class="button button-small">+ ' . esc_html__('Expense', 'comptaflow-by-meetempo') . '</a>';
        echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-pro')) . '" class="button button-primary button-small">' . esc_html__('Dashboard', 'comptaflow-by-meetempo') . '</a>';
        echo '</div>';
        
        echo '</div>';
    }
    
    /**
     * Quick stats for the widget
     */
    private static function getQuickStats(): array {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfp_';
        $user_id = get_current_user_id();
        
        $start_month = gmdate('Y-m-01');
        $end_month = gmdate('Y-m-t');
        
        // Monthly revenue
        $ca_month = $wpdb->get_var($wpdb->prepare(
            "SELECT COALESCE(SUM(amount_ht), 0) FROM {$prefix}transactions 
             WHERE type = 'SALE' AND created_by = %d 
             AND date_txn BETWEEN %s AND %s",
            $user_id, $start_month, $end_month
        ));
        
        // VAT collected
        $tva_collected = $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, $start_month, $end_month
        ));
        
        // VAT deductible
        $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, $start_month, $end_month
        ));
        
        return [
            'ca_month' => floatval($ca_month),
            'tva_collected' => floatval($tva_collected),
            'tva_deductible' => floatval($tva_deductible)
        ];
    }
    
    /**
     * Count pending transactions
     */
    private static function getPendingTransactions(): int {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfp_';
        
        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$prefix}transactions 
             WHERE created_by = %d AND payment_status = 'PENDING'",
            get_current_user_id()
        ));
        
        return intval($count);
    }

    /**
     * Enqueue admin scripts and styles
     */
    public static function enqueueAdminAssets($hook): void {
        // Only load on ComptaFlow pages
        if (strpos($hook, 'comptaflow') === false && strpos($hook, 'page_comptaflow') === false) {
            return;
        }
        
        // Admin CSS
        wp_enqueue_style(
            'comptaflow-admin',
            COMPTAFLOW_PLUGIN_URL . 'assets/css/admin.css',
            [],
            '1.0.3'
        );
        
        // Admin JS
        wp_enqueue_script(
            'comptaflow-admin',
            COMPTAFLOW_PLUGIN_URL . 'assets/js/admin.js',
            ['jquery'],
            '1.0.3',
            true
        );
    }
}
