<?php
// File: src/Admin/Screens/DashboardScreen.php
// ComptaFlow UK Lite - Dashboard Screen

namespace ComptaFlowUK\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-uk-by-meetempo'));
        }
        
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('ComptaFlow UK - Dashboard', 'comptaflow-uk-by-meetempo') . '</h1>';
        
        self::renderLiteInfo();
        self::renderActivityOverview();
        self::renderMainKPIs();
        self::renderUpcomingDeadlines();
        self::renderPendingTransactions();
        self::renderQuickActions();
        
        echo '</div>';
    }
    
    private static function renderLiteInfo(): void {
        $dismissed = get_option('comptaflow_uk_lite_info_dismissed', false);
        if ($dismissed) {
            return;
        }

        echo '<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; margin: 20px 0; border-radius: 8px; color: white; position: relative;">';
        echo '<h2 style="margin-top: 0; color: white;">' . esc_html__('Welcome to ComptaFlow UK!', 'comptaflow-uk-by-meetempo') . '</h2>';
        echo '<p style="color: rgba(255,255,255,0.9);">' . esc_html__('Record your income and expenses, manage invoices and clients, view your journal entries, and export your data.', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</div>';
    }
    
    private static function renderActivityOverview(): void {
        $usage = self::getTransactionUsage();

        echo '<div style="background: #f0f0f1; padding: 15px; margin: 20px 0; border-left: 4px solid #0073aa;">';
        echo '<p><strong>' . esc_html__('Activity:', 'comptaflow-uk-by-meetempo') . '</strong> ' . esc_html($usage) . ' ' . esc_html__('transactions this month', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</div>';
    }
    
    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-uk-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 1200', 'comptaflow-uk-by-meetempo') . '</small>';
        echo '</div>';
        
        // Revenue this month
        $ca_evolution = $stats['ca_previous_month'] > 0 
            ? round((($stats['ca_month'] - $stats['ca_previous_month']) / $stats['ca_previous_month']) * 100, 1)
            : 0;
        $evolution_color = $ca_evolution >= 0 ? '#00a32a' : '#d63638';
        $evolution_sign = $ca_evolution >= 0 ? '+' : '';
        
        echo '<div style="background: white; padding: 20px; border: 1px solid #ddd; border-radius: 4px;">';
        echo '<h3 style="margin-top: 0; color: #00a32a;">' . esc_html__('Revenue this month', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<p style="font-size: 24px; font-weight: bold; margin: 0;">£' . esc_html(number_format($stats['ca_month'], 2, '.', ',')) . '</p>';
        if ($stats['ca_previous_month'] > 0) {
            echo '<small style="color: ' . esc_attr($evolution_color) . ';">' . esc_html($evolution_sign . $ca_evolution) . '% ' . esc_html__('vs last month', 'comptaflow-uk-by-meetempo') . '</small>';
        }
        echo '</div>';
        
        // Output VAT
        echo '<div style="background: white; padding: 20px; border: 1px solid #ddd; border-radius: 4px;">';
        echo '<h3 style="margin-top: 0; color: #dba617;">' . esc_html__('Output VAT', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<p style="font-size: 24px; font-weight: bold; margin: 0;">£' . esc_html(number_format($stats['tva_collected'], 2, '.', ',')) . '</p>';
        echo '<small style="color: #666;">' . esc_html__('Collected this month', 'comptaflow-uk-by-meetempo') . '</small>';
        echo '</div>';
        
        // Input VAT
        echo '<div style="background: white; padding: 20px; border: 1px solid #ddd; border-radius: 4px;">';
        echo '<h3 style="margin-top: 0; color: #d63638;">' . esc_html__('Input VAT', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<p style="font-size: 24px; font-weight: bold; margin: 0;">£' . esc_html(number_format($stats['tva_deductible'], 2, '.', ',')) . '</p>';
        echo '<small style="color: #666;">' . esc_html__('Reclaimable this month', 'comptaflow-uk-by-meetempo') . '</small>';
        echo '</div>';
        
        echo '</div>';
    }
    
    private static function renderUpcomingDeadlines(): void {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfuk_';
        $user_id = get_current_user_id();
        
        $today = gmdate('Y-m-d');
        
        // Next VAT deadline
        $next_vat = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$prefix}vat_periods
             WHERE user_id = %d 
             AND status = 'OPEN'
             AND due_date >= %s
             ORDER BY due_date ASC
             LIMIT 1",
            $user_id, $today
        ), ARRAY_A);
        
        if (empty($next_vat)) {
            return;
        }
        
        echo '<div style="margin: 20px 0; background: #fff; border: 1px solid #ccd0d4; border-radius: 4px;">';
        echo '<h2 style="margin: 0; padding: 15px; background: #f0f0f1; border-bottom: 1px solid #ccd0d4;">';
        echo '📅 ' . esc_html__('Upcoming deadlines', 'comptaflow-uk-by-meetempo');
        echo '</h2>';
        echo '<div style="padding: 20px;">';
        
        // VAT deadline
        $days_until_vat = floor((strtotime($next_vat['due_date']) - time()) / 86400);
        $vat_color = $days_until_vat <= 7 ? '#d63638' : '#0073aa';
        $vat_bg = $days_until_vat <= 7 ? '#f8d7da' : '#cce5ff';
        
        echo '<div style="background: ' . esc_attr($vat_bg) . '; padding: 15px; border-radius: 4px; border-left: 4px solid ' . esc_attr($vat_color) . ';">';
        echo '<h4 style="margin: 0 0 10px 0; color: ' . esc_attr($vat_color) . ';">📋 ' . esc_html__('Next VAT Return', 'comptaflow-uk-by-meetempo') . '</h4>';
        echo '<p style="margin: 0;">';
        echo '<strong>' . esc_html__('Period:', 'comptaflow-uk-by-meetempo') . '</strong> ' . esc_html($next_vat['period']) . '<br>';
        echo '<strong>' . esc_html__('Due date:', 'comptaflow-uk-by-meetempo') . '</strong> ' . esc_html(date_i18n('d/m/Y', strtotime($next_vat['due_date'])));
        if ($days_until_vat <= 7) {
            /* translators: %d: number of days */
            echo ' <span style="color: #d63638; font-weight: bold;">' . sprintf(esc_html__('(in %d days!)', 'comptaflow-uk-by-meetempo'), intval($days_until_vat)) . '</span>';
        } else {
            /* translators: %d: number of days */
            echo ' <span style="color: #666;">' . sprintf(esc_html__('(in %d days)', 'comptaflow-uk-by-meetempo'), intval($days_until_vat)) . '</span>';
        }
        echo '</p>';
        echo '<p style="margin: 10px 0 0 0;"><a href="?page=comptaflow-uk-vat-returns" class="button button-small">' . esc_html__('View VAT Returns', 'comptaflow-uk-by-meetempo') . '</a></p>';
        echo '</div>';
        
        echo '</div>';
        echo '</div>';
    }
    
    private static function renderPendingTransactions(): void {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfuk_';
        $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__('Transactions awaiting payment', 'comptaflow-uk-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-uk-by-meetempo') . '</h3>';
            echo '<p style="font-size: 28px; font-weight: bold; margin: 10px 0;">£' . esc_html(number_format($pending_sales->total, 2, '.', ',')) . '</p>';
            /* translators: %d: number of pending sales */
            echo '<p style="margin: 10px 0;">' . sprintf(esc_html__('%d pending sale(s)', 'comptaflow-uk-by-meetempo'), intval($pending_sales->count)) . '</p>';
            echo '<a href="?page=comptaflow-uk-sales" class="button button-primary">' . esc_html__('View Sales', 'comptaflow-uk-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-uk-by-meetempo') . '</h3>';
            echo '<p style="font-size: 28px; font-weight: bold; margin: 10px 0;">£' . esc_html(number_format($pending_expenses->total, 2, '.', ',')) . '</p>';
            /* translators: %d: number of pending expenses */
            echo '<p style="margin: 10px 0;">' . sprintf(esc_html__('%d pending expense(s)', 'comptaflow-uk-by-meetempo'), intval($pending_expenses->count)) . '</p>';
            echo '<a href="?page=comptaflow-uk-expenses" class="button button-primary">' . esc_html__('View Expenses', 'comptaflow-uk-by-meetempo') . '</a>';
            echo '</div>';
        }
        
        echo '</div>';
        echo '</div>';
    }
    
    private static function renderQuickActions(): void {
        echo '<div style="margin: 20px 0;">';
        echo '<h2>' . esc_html__('Quick actions', 'comptaflow-uk-by-meetempo') . '</h2>';
        echo '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">';
        
        $actions = [
            ['page' => 'comptaflow-uk-sales&action=new', 'label' => __('+ New income', 'comptaflow-uk-by-meetempo'), 'icon' => '💰'],
            ['page' => 'comptaflow-uk-expenses&action=new', 'label' => __('+ New expense', 'comptaflow-uk-by-meetempo'), 'icon' => '💸'],
            ['page' => 'comptaflow-uk-journal-manual', 'label' => __('+ Manual journal entry', 'comptaflow-uk-by-meetempo'), 'icon' => '📝'],
            ['page' => 'comptaflow-uk-vat-returns', 'label' => __('VAT Returns', 'comptaflow-uk-by-meetempo'), 'icon' => '📋'],
            ['page' => 'comptaflow-uk-journal', 'label' => __('View journal', 'comptaflow-uk-by-meetempo'), 'icon' => '📖'],
            ['page' => 'comptaflow-uk-exports', 'label' => __('Export data', 'comptaflow-uk-by-meetempo'), 'icon' => '📤'],
        ];
        
        foreach ($actions as $action) {
            echo '<a href="?page=' . esc_attr($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>';
    }
    
    private static function getTransactionUsage(): int {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfuk_';
        
        $start_of_month = gmdate('Y-m-01');
        $end_of_month = gmdate('Y-m-t');
        
        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$prefix}transactions 
             WHERE created_by = %d 
             AND date_txn BETWEEN %s AND %s",
            get_current_user_id(),
            $start_of_month,
            $end_of_month
        ));
        
        return intval($count);
    }
    
    private static function calculateMainKPIs(): 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');
        $start_previous = gmdate('Y-m-01', strtotime('-1 month'));
        $end_previous = gmdate('Y-m-t', strtotime('-1 month'));
        
        // Bank balance (1200)
        $bank_like = $wpdb->esc_like('1200') . '%';
        $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",
            $bank_like, $user_id
        ));
        
        // Revenue this month
        $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
        ));
        
        // Revenue previous month
        $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
        ));
        
        // Output 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
        ));
        
        // Input VAT (reclaimable)
        $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),
        ];
    }
}
