<?php
if (!defined('ABSPATH')) exit;

/**
 * 1. Helper Function: Get Currency Symbol
 */
if (!function_exists('get_afdp_currency_symbol')) {
    function get_afdp_currency_symbol() {
        $currency_code = get_option('afdp_currency', 'USD');
        $symbols = [
            'USD' => '$', 'GBP' => '£', 'EUR' => '€', 'INR' => '₹', 'BDT' => '৳',
            'AUD' => 'A$', 'CAD' => 'C$', 'JPY' => '¥', 'AED' => 'د.إ', 'SAR' => 'SR'
        ];
        return isset($symbols[$currency_code]) ? $symbols[$currency_code] : $currency_code;
    }
}

/**
 * 2. Main Dashboard Layout (Professional Modern Design)
 */
function afdp_dashboard_tab() {
    // --- DATA CALCULATIONS (Kept identical to your logic) ---
    $afdp_currency = get_afdp_currency_symbol();
    
    $today_args = [
        'post_type'   => 'afdp_food_order',
        'post_status' => 'publish',
        'numberposts' => -1,
        'date_query'  => [['year' => gmdate('Y'), 'month' => gmdate('m'), 'day' => gmdate('d')]],
    ];

    $todays_orders   = get_posts($today_args);
    $todays_count    = count($todays_orders);
    $todays_revenue  = 0;
    $product_stats   = [];
    $category_stats  = [];

    foreach($todays_orders as $o) {
        $todays_revenue += (float)get_post_meta($o->ID, 'afdp_total_price', true);
        $items = get_post_meta($o->ID, 'afdp_order_items', true);
        
        if (is_array($items)) {
            foreach ($items as $item) {
                $name = $item['name'] ?? 'Unknown';
                $qty  = intval($item['qty'] ?? 1);
                $product_stats[$name] = ($product_stats[$name] ?? 0) + $qty;
                
                $product_posts = get_posts( array( 'title' => $name, 'post_type' => 'afdp_food_item', 'posts_per_page' => 1 ) );
                $product_obj   = ! empty( $product_posts ) ? $product_posts[0] : null;
                if ($product_obj) {
                    $terms = wp_get_post_terms($product_obj->ID, 'afdp_food_category');
                    if (!empty($terms)) {
                        $cat_name = $terms[0]->name;
                        $category_stats[$cat_name] = ($category_stats[$cat_name] ?? 0) + $qty;
                    }
                }
            }
        }
    }
    arsort($product_stats);
    arsort($category_stats);

    $pending_orders_count = count(get_posts([
        'post_type'   => 'afdp_food_order',
        'post_status' => 'publish',
        'numberposts' => -1,
        'meta_query'  => [['key' => 'afdp_order_status', 'value' => 'pending']]
    ]));

    $all_orders_url = admin_url('admin.php?page=awesome_food_delivery&tab=orders');
    ?>

    <style>
        :root {
            --afdp-brand: #2271b1;
            --afdp-danger: #e53935;
            --afdp-success: #10b981;
            --afdp-dark: #1e293b;
            --afdp-slate: #64748b;
            --afdp-border: #e2e8f0;
            --afdp-bg-light: #f8fafc;
        }

        .afdp-dash-wrap { padding: 10px 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }

        /* HEADER SECTION */
        .afdp-header-flex { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 25px; }
        .afdp-title-area h2 { font-size: 22px; font-weight: 800; margin: 0; color: var(--afdp-dark); }
        .afdp-title-area p { margin: 5px 0 0; color: var(--afdp-slate); font-size: 14px; }
        
        .afdp-clock-box { 
            display: flex; gap: 10px; background: #fff; padding: 10px 15px; border-radius: 10px; 
            border: 1px solid var(--afdp-border); box-shadow: 0 2px 4px rgba(0,0,0,0.03);
        }
        .afdp-clock-item { display: flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 600; color: var(--afdp-slate); }
        #afdp-live-clock { color: var(--afdp-brand); font-family: monospace; font-size: 14px; }

        /* LIVE ALERT BANNER */
        .afdp-banner {
            background: #fff; border-radius: 12px; padding: 20px 25px; margin-bottom: 25px;
            display: flex; align-items: center; justify-content: space-between;
            border: 1px solid var(--afdp-border); border-left: 5px solid var(--afdp-danger);
            box-shadow: 0 4px 12px rgba(0,0,0,0.03);
        }
        .afdp-banner.safe { border-left-color: var(--afdp-success); }
        
        .afdp-alert-content { display: flex; align-items: center; gap: 15px; }
        .afdp-bell-icon { 
            width: 45px; height: 45px; border-radius: 10px; display: flex; align-items: center; justify-content: center;
            background: #fff1f2; color: var(--afdp-danger); position: relative;
        }
        .afdp-banner.safe .afdp-bell-icon { background: #ecfdf5; color: var(--afdp-success); }

        /* PULSE ANIMATION */
        .afdp-pulse-dot {
            position: absolute; top: -3px; right: -3px; width: 12px; height: 12px; 
            background: var(--afdp-danger); border-radius: 50%; border: 2px solid #fff;
            animation: afdp-pulse-key 2s infinite;
        }
        @keyframes afdp-pulse-key {
            0% { transform: scale(0.9); box-shadow: 0 0 0 0 rgba(229, 57, 53, 0.7); }
            70% { transform: scale(1); box-shadow: 0 0 0 10px rgba(229, 57, 53, 0); }
            100% { transform: scale(0.9); box-shadow: 0 0 0 0 rgba(229, 57, 53, 0); }
        }

        /* STATS CARDS */
        .afdp-stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 30px; }
        .afdp-stat-card { 
            background: #fff; padding: 20px; border-radius: 12px; border: 1px solid var(--afdp-border);
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .afdp-stat-card:hover { transform: translateY(-3px); box-shadow: 0 8px 15px rgba(0,0,0,0.05); }
        .afdp-stat-label { font-size: 12px; font-weight: 700; color: var(--afdp-slate); text-transform: uppercase; display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
        .afdp-stat-value { font-size: 28px; font-weight: 800; color: var(--afdp-dark); }

        /* TABLES/LISTS */
        .afdp-columns { display: grid; grid-template-columns: 1fr 1fr; gap: 25px; }
        .afdp-card { background: #fff; border-radius: 12px; border: 1px solid var(--afdp-border); overflow: hidden; }
        .afdp-card-header { background: var(--afdp-bg-light); padding: 15px 20px; border-bottom: 1px solid var(--afdp-border); }
        .afdp-card-header h3 { margin: 0; font-size: 14px; font-weight: 700; color: var(--afdp-dark); text-transform: uppercase; }
        
        .afdp-list-item { 
            display: flex; justify-content: space-between; align-items: center; 
            padding: 12px 20px; border-bottom: 1px solid var(--afdp-bg-light);
        }
        .afdp-badge { background: #f1f5f9; padding: 4px 10px; border-radius: 6px; font-size: 12px; font-weight: 700; color: var(--afdp-slate); }
        .afdp-badge-red { background: #fee2e2; color: var(--afdp-danger); }

        .afdp-btn {
            background: var(--afdp-dark); color: #fff !important; text-decoration: none;
            padding: 10px 18px; border-radius: 8px; font-weight: 600; font-size: 13px;
            display: inline-flex; align-items: center; gap: 8px; transition: opacity 0.2s;
        }
        .afdp-btn:hover { opacity: 0.85; }
    </style>

    <div class="afdp-dash-wrap">
        
        <div class="afdp-header-flex">
            <div class="afdp-title-area">
                <h2>Restaurant Dashboard</h2>
                <p>Real-time analytics and kitchen status.</p>
            </div>
            <div class="afdp-clock-box">
                <div class="afdp-clock-item">
                    <span class="dashicons dashicons-calendar-alt"></span>
                    <?php echo esc_html( gmdate( 'M d, Y' ) ); ?>
                </div>
                <div style="width: 1px; background: var(--afdp-border);"></div>
                <div class="afdp-clock-item">
                    <span class="dashicons dashicons-clock"></span>
                    <span id="afdp-live-clock">00:00:00 AM</span>
                </div>
            </div>
        </div>

        <div class="afdp-banner <?php echo ($pending_orders_count === 0) ? 'safe' : ''; ?>">
            <div class="afdp-alert-content">
                <div class="afdp-bell-icon">
                    <span class="dashicons dashicons-bell"></span>
                    <?php if ($pending_orders_count > 0) : ?><span class="afdp-pulse-dot"></span><?php endif; ?>
                </div>
                <div>
                    <h4 style="margin:0; font-size:18px; font-weight:700;"><?php echo esc_html( $pending_orders_count ); ?> Pending Orders</h4>
                    <p style="margin:2px 0 0; color:var(--afdp-slate); font-size:13px;">Action required for incoming food requests.</p>
                </div>
            </div>
            <a href="<?php echo esc_url($all_orders_url); ?>" class="afdp-btn">
                View All Orders <span class="dashicons dashicons-arrow-right-alt2"></span>
            </a>
        </div>

        <div class="afdp-stats-grid">
            <div class="afdp-stat-card">
                <div class="afdp-stat-label"><span class="dashicons dashicons-cart"></span> Orders Today</div>
                <div class="afdp-stat-value"><?php echo esc_html( $todays_count ); ?></div>
            </div>
            <div class="afdp-stat-card">
                <div class="afdp-stat-label"><span class="dashicons dashicons-chart-line"></span> Daily Revenue</div>
                <div class="afdp-stat-value">
                    <?php echo esc_html( $afdp_currency . number_format( $todays_revenue, 2 ) ); ?>
                </div>
            </div>
            <div class="afdp-stat-card">
                <div class="afdp-stat-label"><span class="dashicons dashicons-cloud"></span> System</div>
                <div class="afdp-stat-value" style="color: var(--afdp-success); font-size: 20px;">● Live</div>
            </div>
        </div>

        <div class="afdp-columns">
            <div class="afdp-card">
                <div class="afdp-card-header"><h3>Top Items Today</h3></div>
                <?php if (!empty($product_stats)) : 
                    foreach (array_slice($product_stats, 0, 5) as $name => $qty) : ?>
                    <div class="afdp-list-item">
                        <span style="font-weight:600; color: var(--afdp-dark);"><?php echo esc_html($name); ?></span>
                        <span class="afdp-badge afdp-badge-red"><?php echo esc_html($qty); ?> Sold</span>
                    </div>
                <?php endforeach; else : ?>
                    <p style="padding:20px; color:var(--afdp-slate); font-size:13px;">No items sold today yet.</p>
                <?php endif; ?>
            </div>

            <div class="afdp-card">
                <div class="afdp-card-header"><h3>Popular Categories</h3></div>
                <?php if (!empty($category_stats)) : 
                    foreach (array_slice($category_stats, 0, 5) as $cat => $qty) : ?>
                    <div class="afdp-list-item">
                        <span style="font-weight:600; color: var(--afdp-dark);"><?php echo esc_html($cat); ?></span>
                        <span class="afdp-badge"><?php echo esc_html($qty); ?> Orders</span>
                    </div>
                <?php endforeach; else : ?>
                    <p style="padding:20px; color:var(--afdp-slate); font-size:13px;">No category data available.</p>
                <?php endif; ?>
            </div>
        </div>

    </div>

    <script>
    function afdpRunClock() {
        const now = new Date();
        let h = now.getHours();
        const m = String(now.getMinutes()).padStart(2, '0');
        const s = String(now.getSeconds()).padStart(2, '0');
        const ampm = h >= 12 ? 'PM' : 'AM';
        h = h % 12; h = h ? h : 12;
        const timeStr = h + ':' + m + ':' + s + ' ' + ampm;
        const el = document.getElementById('afdp-live-clock');
        if(el) el.textContent = timeStr;
    }
    setInterval(afdpRunClock, 1000);
    afdpRunClock();
    </script>
    <?php
}