<?php
require 'auth_check.php';
require '../config/db.php';

// --- 1. HANDLE QUICK COUPON CREATION ---
$msg = "";
$msgClass = "";
if (isset($_POST['create_quick_coupon'])) {
    $code = strtoupper(trim($_POST['code']));
    $type = $_POST['type'];
    $value = $_POST['value'];
    
    $check = $pdo->prepare("SELECT id FROM coupons WHERE code = ?");
    $check->execute([$code]);
    
    if($check->rowCount() == 0) {
        $stmt = $pdo->prepare("INSERT INTO coupons (code, type, value) VALUES (?, ?, ?)");
        if($stmt->execute([$code, $type, $value])) {
            $msg = "Success! Coupon <strong>$code</strong> created."; $msgClass = "success";
        } else { $msg = "Error."; $msgClass = "error"; }
    } else { $msg = "Code exists."; $msgClass = "error"; }
}

// --- 2. FETCH DASHBOARD STATS ---
$totalOrders = $pdo->query("SELECT COUNT(*) FROM orders")->fetchColumn();
$totalRevenue = $pdo->query("SELECT SUM(total_amount) FROM orders WHERE status != 'cancelled'")->fetchColumn();
$pendingOrders = $pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'pending'")->fetchColumn();
$productsCount = $pdo->query("SELECT COUNT(*) FROM products WHERE is_active = 1")->fetchColumn();
$totalPosts = $pdo->query("SELECT COUNT(*) FROM posts")->fetchColumn();
$totalViews = $pdo->query("SELECT SUM(views) FROM posts")->fetchColumn();

// --- 3. FETCH CHART DATA (LAST 7 DAYS) ---
$dates = [];
$revenues = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $stmt = $pdo->prepare("SELECT SUM(total_amount) FROM orders WHERE DATE(created_at) = ? AND status != 'cancelled'");
    $stmt->execute([$date]);
    $day_total = $stmt->fetchColumn() ?: 0;
    
    $dates[] = date('d M', strtotime($date));
    $revenues[] = $day_total;
}

// --- 4. FETCH RECENT ORDERS ---
$orders = $pdo->query("SELECT o.*, u.name as user_name FROM orders o LEFT JOIN users u ON o.user_id = u.id ORDER BY o.created_at DESC LIMIT 5")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Admin Dashboard - Pro Subscription Offers</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        .msg-box { padding: 10px; border-radius: 5px; margin-bottom: 20px; font-size: 14px; text-align: center; }
        .success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        
        /* Grid Layout */
        .dashboard-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-top: 30px; }
        
        /* Chart Container (FIXED HEIGHT) */
        .chart-container { 
            background: white; 
            padding: 20px; 
            border-radius: 8px; 
            box-shadow: 0 4px 15px rgba(0,0,0,0.05); 
            margin-top: 30px; 
            height: 400px; /* Forces the box to stay nice and compact */
            position: relative;
        }
        
        /* Styles for Coupon Card & Inputs */
        .coupon-card { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); border-top: 4px solid #9b59b6; }
        .input-group { margin-bottom: 15px; }
        .form-control { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        .btn-gen { background: #ecf0f1; border: 1px solid #bdc3c7; color: #2c3e50; padding: 5px 10px; font-size: 12px; cursor: pointer; border-radius: 4px; margin-top: 5px; }
        
        /* Stats Cards */
        .card { border-top: 4px solid #ddd; transition: transform 0.2s; }
        .card:hover { transform: translateY(-5px); }
        .card-blue { border-top-color: #3498db; }
        .card-green { border-top-color: #2ecc71; }
        .card-orange { border-top-color: #f39c12; }
        .card-purple { border-top-color: #8e44ad; }
        .card small { display: block; margin-top: 5px; color: #777; font-size: 13px; }

        @media (max-width: 900px) { .dashboard-grid { grid-template-columns: 1fr; } }
    </style>
</head>
<body>

    <div class="sidebar">
        <?php include 'sidebar.php'; ?>
    </div>
    <div class="content">
        <div class="header"><h1>Dashboard Overview</h1></div>
        <?php if($msg): ?><div class="msg-box <?php echo $msgClass; ?>"><?php echo $msg; ?></div><?php endif; ?>

        <div class="card-grid">
            <div class="card card-blue">
                <h3>Total Orders</h3>
                <span class="number"><?php echo number_format($totalOrders); ?></span>
                <small>Pending: <span style="color:orange"><?php echo $pendingOrders; ?></span></small>
            </div>
            <div class="card card-green">
                <h3>Revenue</h3>
                <span class="number">₹<?php echo number_format($totalRevenue); ?></span>
            </div>
            <div class="card card-purple">
                <h3>Blog</h3>
                <span class="number"><?php echo number_format($totalPosts); ?> Posts</span>
                <small><?php echo number_format($totalViews); ?> Views</small>
            </div>
            <div class="card card-orange">
                <h3>Inventory</h3>
                <span class="number"><?php echo number_format($productsCount); ?></span>
            </div>
        </div>

        <div class="chart-container">
            <h3 style="margin-top: 0; color: #2c3e50; margin-bottom: 15px;"><i class="fas fa-chart-line"></i> Revenue Trend (7 Days)</h3>
            <div style="height: 300px; width: 100%;">
                <canvas id="salesChart"></canvas>
            </div>
        </div>

        <div class="dashboard-grid">
            <div>
                <h3><i class="fas fa-clock"></i> Recent Orders</h3>
                <table>
                    <thead><tr><th>ID</th><th>Customer</th><th>Amount</th><th>Status</th><th>Action</th></tr></thead>
                    <tbody>
                        <?php if(count($orders) > 0): ?>
                            <?php foreach ($orders as $order): ?>
                            <tr>
                                <td>#<?php echo $order['id']; ?></td>
                                <td><strong><?php echo htmlspecialchars($order['user_name'] ?? 'Guest'); ?></strong></td>
                                <td>₹<?php echo number_format($order['total_amount']); ?></td>
                                <td>
                                    <span style="color: <?php echo ($order['status']=='completed'?'green':($order['status']=='pending'?'orange':'red')); ?>; font-weight: bold; text-transform: capitalize;">
                                        <?php echo $order['status']; ?>
                                    </span>
                                </td>
                                <td><a href="orders.php?id=<?php echo $order['id']; ?>" class="btn btn-primary" style="font-size: 12px; padding: 5px 10px;">Manage</a></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="5" style="text-align:center;">No orders found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
                <div style="margin-top: 15px; text-align: right;">
                    <a href="orders.php" style="color: #3498db; text-decoration: none; font-weight: bold;">View All Orders &rarr;</a>
                </div>
            </div>

            <div>
                <div class="coupon-card" style="margin-bottom: 20px;">
                    <h3 style="margin-top: 0; color: #8e44ad;"><i class="fas fa-magic"></i> Quick Coupon</h3>
                    <form method="POST">
                        <div class="input-group">
                            <div style="display: flex; gap: 5px;">
                                <input type="text" name="code" id="couponCode" class="form-control" placeholder="e.g. SAVE20" required style="text-transform: uppercase;">
                                <button type="button" class="btn-gen" onclick="generateCode()"><i class="fas fa-random"></i></button>
                            </div>
                        </div>
                        <div style="display: flex; gap: 10px;">
                            <select name="type" class="form-control"><option value="fixed">Flat ₹</option><option value="percent">% Off</option></select>
                            <input type="number" name="value" class="form-control" placeholder="Val" required>
                        </div>
                        <button type="submit" name="create_quick_coupon" class="btn btn-primary" style="width: 100%; background: #9b59b6; border: none; margin-top: 10px;">Create</button>
                    </form>
                </div>
                <a href="blog_editor.php" style="display: block; background: #34495e; color: white; padding: 15px; border-radius: 8px; text-align: center; text-decoration: none; font-weight: bold;">
                    <i class="fas fa-pen-nib"></i> Write New Article
                </a>
            </div>
        </div>
    </div>

    <script>
        function generateCode() {
            const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            let result = "SALE-";
            for (let i = 0; i < 5; i++) { result += chars.charAt(Math.floor(Math.random() * chars.length)); }
            document.getElementById("couponCode").value = result;
        }

        // CHART CONFIGURATION
        const ctx = document.getElementById('salesChart').getContext('2d');
        const salesChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: <?php echo json_encode($dates); ?>, 
                datasets: [{
                    label: 'Revenue (₹)',
                    data: <?php echo json_encode($revenues); ?>, 
                    borderColor: '#2ecc71',
                    backgroundColor: 'rgba(46, 204, 113, 0.1)', // Lighter background
                    borderWidth: 3,
                    pointBackgroundColor: '#27ae60',
                    fill: true,
                    tension: 0.4 // Smooth curves
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false, // FIX: Allows chart to fit container height
                plugins: {
                    legend: { display: false } // Hide label to save space
                },
                scales: {
                    y: { 
                        beginAtZero: true,
                        grid: { borderDash: [5, 5] } // Dotted lines
                    },
                    x: {
                        grid: { display: false }
                    }
                }
            }
        });
    </script>

</body>
</html>