<?php
namespace ComptaFlowUK;

use ComptaFlowUK\Services\DB;
use ComptaFlowUK\Admin\Menu;
use ComptaFlowUK\Security\Capabilities;

defined('ABSPATH') || exit;

class Bootstrap {
    
    public static function init(): void {
        register_activation_hook(COMPTAFLOW_UK_PLUGIN_FILE, [self::class, 'activate']);
        register_deactivation_hook(COMPTAFLOW_UK_PLUGIN_FILE, [self::class, 'deactivate']);
        
        add_action('admin_menu', [Menu::class, 'register']);
        add_action('wp_dashboard_setup', [self::class, 'addDashboardWidget']);
        add_action('admin_enqueue_scripts', [self::class, 'enqueueAdminAssets']);
        
        \ComptaFlowUK\Services\ExportHandler::register();
        \ComptaFlowUK\Admin\Actions\PDFActions::boot();

        add_action('comptaflow_uk_daily_check', [\ComptaFlowUK\Services\InvoiceService::class, 'checkOverdue']);
        if (!wp_next_scheduled('comptaflow_uk_daily_check')) {
            wp_schedule_event(time(), 'daily', 'comptaflow_uk_daily_check');
        }

        Capabilities::init();
    }
    
    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_uk_widget',
            __('ComptaFlow UK - This Month\'s Tasks', 'comptaflow-uk-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-uk-by-meetempo') . '</small>';
        echo '</div>';
        echo '<div style="text-align: center;">';
        $vat_balance = $stats['tva_collected'] - $stats['tva_deductible'];
        $color = $vat_balance >= 0 ? '#d63638' : '#00a32a';
        echo '<strong style="font-size: 18px; color: ' . esc_attr($color) . ';">' . '£' . esc_html(number_format(abs($vat_balance), 0)) . '</strong><br>';
        echo '<small>' . esc_html($vat_balance >= 0 ? __('VAT to pay', 'comptaflow-uk-by-meetempo') : __('VAT credit', 'comptaflow-uk-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-uk-by-meetempo')),
                intval($pending_count)
            ) . '</strong><br>';
            echo '<small>' . esc_html__('Invoices awaiting collection or payment', 'comptaflow-uk-by-meetempo') . '</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-uk-sales&action=new')) . '" class="button button-small">+ ' . esc_html__('Sale', 'comptaflow-uk-by-meetempo') . '</a>';
        echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-uk-expenses&action=new')) . '" class="button button-small">+ ' . esc_html__('Expense', 'comptaflow-uk-by-meetempo') . '</a>';
        echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-uk')) . '" class="button button-primary button-small">' . esc_html__('Dashboard', 'comptaflow-uk-by-meetempo') . '</a>';
        echo '</div>';
        
        echo '</div>';
    }
    
    /**
     * Quick stats for the widget
     */
    private static function getQuickStats(): array {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfuk_';
        $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 . 'cfuk_';
        
        $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-uk') === false && strpos($hook, 'page_comptaflow') === false) {
            return;
        }
        
        // Admin CSS
        wp_enqueue_style(
            'comptaflow-uk-admin',
            COMPTAFLOW_UK_PLUGIN_URL . 'assets/css/admin.css',
            [],
            '1.0.0'
        );

        // Media library for logo upload
        wp_enqueue_media();

        // Admin JS
        wp_enqueue_script(
            'comptaflow-uk-admin',
            COMPTAFLOW_UK_PLUGIN_URL . 'assets/js/admin.js',
            ['jquery'],
            '1.0.0',
            true
        );

        // Logo upload JS (Settings page)
        wp_enqueue_script(
            'comptaflow-uk-logo-upload',
            COMPTAFLOW_UK_PLUGIN_URL . 'assets/js/logo-upload.js',
            ['jquery'],
            '1.0.0',
            true
        );
    }
}
