<?php
namespace ComptaFlowPro\Admin\Screens;

defined('ABSPATH') || exit;

class DashboardScreen {
    
    public static function render(): void
    {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions.', 'comptaflow-by-meetempo'));
        }
        
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('ComptaFlow - Dashboard', 'comptaflow-by-meetempo') . '</h1>';
        
        self::renderLiteInfo();
        self::renderOnboarding();
        self::renderMainKPIs();
        self::renderPendingTransactions();
        self::renderQuickActions();
        
        echo '</div>';
    }
    
    /**
 * Render LITE version info with upsell
 */
private static function renderLiteInfo(): void {
    echo '<div style="background: #f0f7ff; padding: 15px; margin: 20px 0; border-left: 4px solid #0073aa; border-radius: 4px;">';
    echo '<h2 style="margin-top: 0;">' . esc_html__('ComptaFlow Lite', 'comptaflow-by-meetempo') . '</h2>';
    echo '<p>' . esc_html__('You are using the free version of ComptaFlow with unlimited transactions.', 'comptaflow-by-meetempo') . '</p>';
    echo '<p style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 8px 16px; border-radius: 20px; display: inline-block; font-weight: 600; margin-bottom: 10px;">';
    echo '🎁 ' . esc_html__('30-day free trial — No credit card required', 'comptaflow-by-meetempo');
    echo '</p><br>';
    echo '<p><a href="' . esc_url(admin_url('admin.php?page=comptaflow-plans')) . '" class="button button-primary">' . esc_html__('Discover Pro Features', 'comptaflow-by-meetempo') . '</a></p>';
    echo '</div>';
    
    // Compact Pro upsell
    echo '<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 12px 20px; margin: 20px 0; border-radius: 8px; color: white; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 10px;">';
    echo '<span style="font-size: 15px;">🚀 <strong>' . esc_html__('Pro', 'comptaflow-by-meetempo') . '</strong> — ' . esc_html__('Invoicing, FEC, Bank Reconciliation, VAT, and more.', 'comptaflow-by-meetempo') . ' <span style="background: rgba(255,255,255,0.2); padding: 2px 8px; border-radius: 10px; font-size: 12px;">' . esc_html__('30 days free — No card required', 'comptaflow-by-meetempo') . '</span></span>';
    echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-plans')) . '" class="button" style="background: white; color: #667eea; border: none; font-weight: 600;">' . esc_html__('Discover Pro →', 'comptaflow-by-meetempo') . '</a>';
    echo '</div>';
}
    /**
     * Render onboarding for new users
     */
    private static function renderOnboarding(): void {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfp_';
        $user_id = get_current_user_id();
        
        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$prefix}transactions WHERE created_by = %d",
            $user_id
        ));
        
        if (intval($count) > 0) {
            return;
        }
        
        echo '<div style="background: #e8f5e9; padding: 20px; margin: 20px 0; border-left: 4px solid #4caf50; border-radius: 4px;">';
        echo '<h2 style="margin-top: 0; color: #2e7d32;">👋 ' . esc_html__('Welcome to ComptaFlow!', 'comptaflow-by-meetempo') . '</h2>';
        echo '<p>' . esc_html__('Get started in 3 steps:', 'comptaflow-by-meetempo') . '</p>';
        echo '<p><strong>1.</strong> <a href="' . esc_url(admin_url('admin.php?page=comptaflow-settings')) . '">' . esc_html__('Configure your company (SIRET, VAT regime)', 'comptaflow-by-meetempo') . '</a></p>';
        echo '<p><strong>2.</strong> <a href="' . esc_url(admin_url('admin.php?page=comptaflow-sales&action=new')) . '">' . esc_html__('Enter your first sale', 'comptaflow-by-meetempo') . '</a></p>';
        echo '<p><strong>3.</strong> <a href="' . esc_url(admin_url('admin.php?page=comptaflow-journal')) . '">' . esc_html__('Check your automatic journal entry', 'comptaflow-by-meetempo') . '</a></p>';
        echo '</div>';
    }

    /**
     * Render main KPIs
     */
    private static function renderMainKPIs(): void {
        $stats = self::calculateMainKPIs();
        
        echo '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 20px 0;">';
        
        // Bank balance
        echo '<div style="background: white; padding: 20px; border: 1px solid #ddd; border-radius: 4px;">';
        echo '<h3 style="margin-top: 0; color: #0073aa;">' . esc_html__('Bank Balance', 'comptaflow-by-meetempo') . '</h3>';
        echo '<p style="font-size: 24px; font-weight: bold; margin: 0;">' . esc_html(number_format($stats['bank_balance'], 2, ',', ' ')) . ' €</p>';
        echo '<small style="color: #666;">' . esc_html__('Account 512', 'comptaflow-by-meetempo') . '</small>';
        echo '</div>';
        
        // Monthly revenue
        $ca_evolution = $stats['ca_previous_month'] > 0 
            ? round((($stats['ca_month'] - $stats['ca_previous_month']) / $stats['ca_previous_month']) * 100, 1)
            : 0;
        $ca_color = $ca_evolution >= 0 ? '#00a32a' : '#d63638';
        
        echo '<div style="background: white; padding: 20px; border: 1px solid #ddd; border-radius: 4px;">';
        echo '<h3 style="margin-top: 0; color: #0073aa;">' . esc_html__('Revenue this month', 'comptaflow-by-meetempo') . '</h3>';
        echo '<p style="font-size: 24px; font-weight: bold; margin: 0;">' . esc_html(number_format($stats['ca_month'], 2, ',', ' ')) . ' €</p>';
        echo '<small style="color: ' . esc_attr($ca_color) . ';">';
        echo esc_html(($ca_evolution >= 0 ? '+' : '') . $ca_evolution) . '% ' . esc_html__('vs last month', 'comptaflow-by-meetempo');
        echo '</small>';
        echo '</div>';
        
        // VAT balance
        $solde_tva = $stats['tva_collected'] - $stats['tva_deductible'];
        $solde_color = $solde_tva >= 0 ? '#d63638' : '#00a32a';
        $solde_label = $solde_tva >= 0 ? __('To pay', 'comptaflow-by-meetempo') : __('Credit', 'comptaflow-by-meetempo');
        
        echo '<div style="background: white; padding: 20px; border: 1px solid #ddd; border-radius: 4px;">';
        echo '<h3 style="margin-top: 0; color: ' . esc_attr($solde_color) . ';">' . esc_html__('VAT Balance', 'comptaflow-by-meetempo') . '</h3>';
        echo '<p style="font-size: 24px; font-weight: bold; margin: 0; color: ' . esc_attr($solde_color) . ';">' . esc_html(number_format(abs($solde_tva), 2, ',', ' ')) . ' €</p>';
        echo '<small style="color: #666;">' . esc_html($solde_label) . '</small>';
        echo '</div>';
        
        echo '</div>';
    }
    
    /**
     * Render pending transactions
     */
    private static function renderPendingTransactions(): void {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfp_';
        $user_id = get_current_user_id();
        
        $pending_sales = $wpdb->get_row($wpdb->prepare(
            "SELECT COUNT(*) as count, COALESCE(SUM(amount_ttc), 0) as total
             FROM {$prefix}transactions 
             WHERE type = 'SALE' AND payment_status = 'PENDING' AND created_by = %d",
            $user_id
        ));
        
        $pending_expenses = $wpdb->get_row($wpdb->prepare(
            "SELECT COUNT(*) as count, COALESCE(SUM(amount_ttc), 0) as total
             FROM {$prefix}transactions 
             WHERE type IN ('EXPENSE', 'PAYROLL', 'SOCIAL_PAYMENT', 'TAX_PAYMENT', 'VAT_PAYMENT') 
             AND payment_status = 'PENDING' AND created_by = %d",
            $user_id
        ));
        
        $has_pending = ($pending_sales->count > 0) || ($pending_expenses->count > 0);
        
        if (!$has_pending) {
            return;
        }
        
        echo '<div style="margin: 20px 0;">';
        echo '<h2>' . esc_html__('Pending Transactions', 'comptaflow-by-meetempo') . '</h2>';
        
        echo '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px;">';
        
        if ($pending_sales->count > 0) {
            echo '<div style="background: #e7f5ff; padding: 20px; border-left: 4px solid #0073aa; border-radius: 4px;">';
            echo '<h3 style="margin-top: 0; color: #0073aa;">' . esc_html__('To collect', 'comptaflow-by-meetempo') . '</h3>';
            echo '<p style="font-size: 28px; font-weight: bold; margin: 10px 0;">' . esc_html(number_format($pending_sales->total, 2, ',', ' ')) . ' €</p>';
            echo '<p style="margin: 10px 0;">' . sprintf(
                /* translators: %d: number of invoices */
                esc_html(_n('%d customer invoice', '%d customer invoices', intval($pending_sales->count), 'comptaflow-by-meetempo')),
                intval($pending_sales->count)
            ) . '</p>';
            echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-plans')) . '" class="button">' . esc_html__('Bank Reconciliation (Pro)', 'comptaflow-by-meetempo') . '</a>';
            echo '</div>';
        }
        
        if ($pending_expenses->count > 0) {
            echo '<div style="background: #fff3cd; padding: 20px; border-left: 4px solid #d63638; border-radius: 4px;">';
            echo '<h3 style="margin-top: 0; color: #d63638;">' . esc_html__('To pay', 'comptaflow-by-meetempo') . '</h3>';
            echo '<p style="font-size: 28px; font-weight: bold; margin: 10px 0;">' . esc_html(number_format($pending_expenses->total, 2, ',', ' ')) . ' €</p>';
            echo '<p style="margin: 10px 0;">' . sprintf(
                /* translators: %d: number of invoices */
                esc_html(_n('%d supplier invoice', '%d supplier invoices', intval($pending_expenses->count), 'comptaflow-by-meetempo')),
                intval($pending_expenses->count)
            ) . '</p>';
            echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-plans')) . '" class="button">' . esc_html__('Bank Reconciliation (Pro)', 'comptaflow-by-meetempo') . '</a>';
            echo '</div>';
        }
        
        echo '</div>';
        echo '</div>';
    }
    
    /**
     * Render quick actions
     */
    private static function renderQuickActions(): void {
        echo '<div style="margin: 20px 0;">';
        echo '<h2>' . esc_html__('Quick Actions', 'comptaflow-by-meetempo') . '</h2>';
        echo '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">';
        
        $actions = [
            ['page' => 'comptaflow-sales&action=new', 'label' => __('+ New Sale', 'comptaflow-by-meetempo'), 'icon' => '💰'],
            ['page' => 'comptaflow-expenses&action=new', 'label' => __('+ New Expense', 'comptaflow-by-meetempo'), 'icon' => '💸'],
            ['page' => 'comptaflow-journal-manual', 'label' => __('+ Manual Entry', 'comptaflow-by-meetempo'), 'icon' => '📝'],
            ['page' => 'comptaflow-journal', 'label' => __('View Journal', 'comptaflow-by-meetempo'), 'icon' => '📖'],
            ['page' => 'comptaflow-exports', 'label' => __('Exports', 'comptaflow-by-meetempo'), 'icon' => '📤'],
            ['page' => 'comptaflow-plans', 'label' => __('Go Pro', 'comptaflow-by-meetempo'), 'icon' => '💎'],
        ];
        
        foreach ($actions as $action) {
            echo '<a href="' . esc_url(admin_url('admin.php?page=' . $action['page'])) . '" class="button" style="height: auto; padding: 15px; text-align: center; display: block;">';
            echo '<div style="font-size: 24px; margin-bottom: 8px;">' . esc_html($action['icon']) . '</div>';
            echo '<div>' . esc_html($action['label']) . '</div>';
            echo '</a>';
        }
        
        echo '</div>';
        echo '</div>';
    }
    
    /**
     * Calculate main KPIs
     */
    private static function calculateMainKPIs(): 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');
        $start_previous = gmdate('Y-m-01', strtotime('-1 month'));
        $end_previous = gmdate('Y-m-t', strtotime('-1 month'));
        
        // Bank balance (512)
        $like_512 = $wpdb->esc_like('512') . '%';
        $bank_balance = $wpdb->get_var($wpdb->prepare(
            "SELECT COALESCE(SUM(debit) - SUM(credit), 0) 
             FROM {$prefix}journal_entries 
             WHERE compte_num LIKE %s AND created_by = %d",
            $like_512, $user_id
        ));
        
        // 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
        ));
        
        // Previous month revenue
        $ca_previous = $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_previous, $end_previous
        ));
        
        // 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 [
            'bank_balance' => floatval($bank_balance),
            'ca_month' => floatval($ca_month),
            'ca_previous_month' => floatval($ca_previous),
            'tva_collected' => floatval($tva_collected),
            'tva_deductible' => floatval($tva_deductible),
        ];
    }
}
