<?php
session_start();
require_once 'config.php';

// Auth Check
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? 'User';

// Database Connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Get Balance & Subscription
$stmt = $conn->prepare("SELECT s.tokens_remaining, p.name AS package_name FROM user_subscriptions s JOIN subscription_packages p ON s.package_id = p.id WHERE s.user_id = ? AND s.status = 'active'");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

$balance = 0;
$package = "Free";

if ($row = $res->fetch_assoc()) {
    $balance = number_format($row['tokens_remaining']);
    $package = $row['package_name'];
}
$stmt->close();

// Get Transactions (Limit 5)
$trans_stmt = $conn->prepare("SELECT amount, transaction_type, description, created_at FROM token_transactions WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
$trans_stmt->bind_param("i", $user_id);
$trans_stmt->execute();
$transactions = $trans_stmt->get_result();
$trans_stmt->close();

// Connection will be closed at the end of the script or automatically
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard | SaniBook Kenya</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');

        body {
            font-family: 'Inter', sans-serif;
        }
    </style>
</head>

<body class="bg-slate-50 min-h-screen text-slate-800">

    <?php include 'navbar.php'; ?>
    <?php
    $breadcrumbs = [
        ['label' => 'Home', 'url' => '/'],
        ['label' => 'Dashboard']
    ];
    include 'breadcrumbs.php';
    ?>

    <main class="max-w-7xl mx-auto px-4 py-12">

        <div class="grid grid-cols-1 md:grid-cols-3 gap-8">

            <!-- Left Sidebar: Balance & Transactions -->
            <div class="col-span-1 space-y-6">

                <!-- Balance Card -->
                <div
                    class="bg-gradient-to-br from-[#0f172a] to-blue-900 rounded-2xl p-8 text-white shadow-xl relative overflow-hidden">
                    <div class="absolute top-0 right-0 p-4 opacity-10">
                        <i class="fa-solid fa-coins text-9xl"></i>
                    </div>
                    <div class="relative z-10">
                        <h2 class="text-blue-200 text-sm font-bold uppercase tracking-widest mb-1">Token Balance</h2>
                        <div class="text-5xl font-mono font-bold mb-4">
                            <?php echo $balance; ?>
                        </div>
                        <p class="text-sm text-blue-100 mb-8"><span class="bg-white/10 px-2 py-1 rounded text-xs">
                                <?php echo htmlspecialchars($package); ?> Plan
                            </span></p>

                        <div class="grid grid-cols-2 gap-4">
                            <a href="submit-data.php"
                                class="bg-white text-blue-900 font-bold py-3 text-center rounded-lg hover:bg-blue-50 transition-colors">
                                Submit Data
                            </a>
                            <a href="pricing.php"
                                class="bg-blue-500 text-white font-bold py-3 text-center rounded-lg hover:bg-blue-400 transition-colors">
                                Buy Tokens
                            </a>
                        </div>
                    </div>
                </div>

                <!-- Pending Orders -->
                <?php
                $pending_orders_stmt = $conn->prepare("SELECT id, amount_paid, tokens_requested, created_at FROM token_orders WHERE user_id = ? AND status = 'pending'");
                $pending_orders_stmt->bind_param("i", $user_id);
                $pending_orders_stmt->execute();
                $pending_orders = $pending_orders_stmt->get_result();
                ?>
                <?php if ($pending_orders->num_rows > 0): ?>
                    <div class="bg-amber-50 rounded-2xl border border-amber-200 p-6 shadow-sm mb-6">
                        <h3 class="text-lg font-bold text-amber-800 mb-4 flex items-center gap-2">
                            <i class="fa-solid fa-clock-rotate-left"></i> Pending Orders
                        </h3>
                        <div class="space-y-3">
                            <?php while ($po = $pending_orders->fetch_assoc()): ?>
                                <div class="bg-white p-3 rounded-lg border border-amber-100 flex justify-between items-center">
                                    <div>
                                        <div class="text-sm font-bold text-slate-800">Order #<?= $po['id'] ?></div>
                                        <div class="text-xs text-slate-500"><?= number_format($po['tokens_requested']) ?> Tokens
                                        </div>
                                    </div>
                                    <div class="text-right">
                                        <div class="text-sm font-bold text-amber-600">KES
                                            <?= number_format($po['amount_paid']) ?></div>
                                        <div class="text-xs text-slate-400"><?= date('M j', strtotime($po['created_at'])) ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        </div>
                    </div>
                <?php endif; ?>
                <?php $pending_orders_stmt->close(); ?>

                <!-- Transaction History -->
                <div class="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
                    <h3 class="text-lg font-bold text-slate-800 mb-4">Recent Transactions</h3>

                    <?php if ($transactions->num_rows > 0): ?>
                        <div class="space-y-3">
                            <?php while ($t = $transactions->fetch_assoc()): ?>
                                <div
                                    class="flex items-center justify-between p-3 bg-slate-50 rounded-lg border border-slate-100">
                                    <div class="flex items-center gap-3">
                                        <div
                                            class="w-8 h-8 rounded-full flex items-center justify-center 
                                        <?php echo $t['transaction_type'] == 'debit' ? 'bg-red-100 text-red-500' : 'bg-green-100 text-green-500'; ?>">
                                            <i
                                                class="fa-solid <?php echo $t['transaction_type'] == 'debit' ? 'fa-arrow-up' : 'fa-arrow-down'; ?> text-xs"></i>
                                        </div>
                                        <div>
                                            <p class="font-semibold text-xs text-slate-800">
                                                <?php echo htmlspecialchars($t['description']); ?>
                                            </p>
                                            <p class="text-xs text-slate-500">
                                                <?php echo date('M j, Y', strtotime($t['created_at'])); ?>
                                            </p>
                                        </div>
                                    </div>
                                    <span
                                        class="font-mono font-bold text-sm <?php echo $t['transaction_type'] == 'debit' ? 'text-red-500' : 'text-green-500'; ?>">
                                        <?php echo $t['transaction_type'] == 'debit' ? '-' : '+'; ?>
                                        <?php echo number_format($t['amount']); ?>
                                    </span>
                                </div>
                            <?php endwhile; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-8 text-slate-400">
                            <i class="fa-solid fa-receipt text-3xl mb-2 opacity-50"></i>
                            <p class="text-sm">No transactions yet</p>
                        </div>
                    <?php endif; ?>
                </div>

            </div>

            <!-- Main Content: My Submissions -->
            <div class="col-span-1 md:col-span-2">

                <!-- My Submissions -->
                <div class="bg-white rounded-2xl border border-slate-200 p-8 shadow-sm">
                    <h3 class="text-lg font-bold text-slate-800 mb-6">My data</h3>
                    <?php
                    $sub_stmt = $conn->prepare("SELECT id, title, created_at, is_verified, status, edit_count, IFNULL(view_count, 0) as view_count, IFNULL(last_token_cost, 0) as last_token_cost FROM submissions WHERE user_id = ? ORDER BY created_at DESC LIMIT 10");
                    if (!$sub_stmt) {
                        die("<div class='bg-red-50 text-red-600 p-4 rounded-lg'>Dashboard Error: " . htmlspecialchars($conn->error) . "</div>");
                    }
                    $sub_stmt->bind_param("i", $user_id);
                    $sub_stmt->execute();
                    $submissions_res = $sub_stmt->get_result();
                    ?>

                    <?php if ($submissions_res->num_rows > 0): ?>
                        <div class="grid gap-4">
                            <?php while ($s = $submissions_res->fetch_assoc()): ?>
                                <?php
                                $status = $s['status'] ?? 'pending';
                                $status_config = match ($status) {
                                    'approved' => ['label' => 'Approved', 'color' => 'green', 'icon' => 'fa-circle-check'],
                                    'rejected' => ['label' => 'Needs Changes', 'color' => 'red', 'icon' => 'fa-circle-xmark'],
                                    default => ['label' => 'Under Review', 'color' => 'amber', 'icon' => 'fa-clock']
                                };
                                ?>
                                <div
                                    class="group relative bg-white border border-slate-200 rounded-xl p-5 hover:shadow-lg hover:border-blue-300 transition-all duration-200">
                                    <div class="flex items-start justify-between gap-4">
                                        <div class="flex-1">
                                            <div class="flex items-center gap-3 mb-2">
                                                <h4
                                                    class="font-bold text-slate-900 text-lg group-hover:text-blue-900 transition-colors">
                                                    <?php echo htmlspecialchars(html_entity_decode($s['title'], ENT_QUOTES | ENT_HTML5)); ?>
                                                </h4>
                                                <span
                                                    class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-<?php echo $status_config['color']; ?>-100 text-<?php echo $status_config['color']; ?>-700">
                                                    <i class="fa-solid <?php echo $status_config['icon']; ?>"></i>
                                                    <?php echo $status_config['label']; ?>
                                                </span>
                                            </div>
                                            <div class="flex items-center gap-4 text-sm text-slate-500 mt-2 flex-wrap">
                                                <span class="flex items-center gap-1.5" title="Cost of Submission">
                                                    <i class="fa-solid fa-coins text-slate-400"></i>
                                                    <?php echo $s['last_token_cost'] > 0 ? number_format($s['last_token_cost']) . ' Tokens' : 'Free'; ?>
                                                </span>
                                                <span class="flex items-center gap-1.5">
                                                    <i class="fa-solid fa-calendar text-slate-400"></i>
                                                    <?php echo date('M j, Y', strtotime($s['created_at'])); ?>
                                                </span>
                                                <?php if ($s['edit_count'] > 0): ?>
                                                    <span class="flex items-center gap-1.5">
                                                        <i class="fa-solid fa-pen-to-square text-slate-400"></i>
                                                        Edited <?php echo $s['edit_count']; ?>x
                                                    </span>
                                                <?php endif; ?>
                                                <span class="flex items-center gap-1.5" title="Total views">
                                                    <i class="fa-solid fa-eye text-slate-400"></i>
                                                    <?php echo number_format($s['view_count']); ?> views
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex items-center gap-2">
                                            <a href="view_submission.php?id=<?php echo $s['id']; ?>"
                                                class="flex items-center gap-2 px-4 py-2.5 bg-slate-50 border border-slate-200 text-slate-700 text-sm font-medium rounded-lg hover:bg-slate-100 hover:border-slate-300 transition-all"
                                                title="View">
                                                <i class="fa-solid fa-eye"></i>
                                                <span>View</span>
                                            </a>
                                            <a href="submit-data.php?edit=<?php echo $s['id']; ?>"
                                                class="flex items-center gap-2 px-4 py-2.5 bg-slate-50 border border-slate-200 text-slate-700 text-sm font-medium rounded-lg hover:bg-blue-50 hover:text-blue-900 hover:border-blue-300 transition-all">
                                                <i class="fa-solid fa-pen-to-square"></i>
                                                <span>Edit</span>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-12 text-slate-400">
                            <div class="inline-flex items-center justify-center w-16 h-16 bg-slate-100 rounded-full mb-4">
                                <i class="fa-solid fa-file-pen text-2xl"></i>
                            </div>
                            <p class="text-lg font-medium text-slate-600">No data yet</p>
                            <p class="text-sm mt-1">Start sharing your sanitation experiences</p>
                            <a href="submit-data.php"
                                class="inline-block mt-4 px-6 py-2 bg-blue-900 text-white rounded-lg hover:bg-blue-800 transition-colors">
                                Submit Your First Data
                            </a>
                        </div>
                    <?php endif; ?>
                </div>

            </div>

        </div>

        <!-- Quick Links -->
        <div class="mt-8 grid grid-cols-1 md:grid-cols-3 gap-6">
            <a href="submit-data.php"
                class="group block p-6 bg-white rounded-xl border border-slate-200 hover:border-blue-500 hover:shadow-md transition-all">
                <div class="flex items-center gap-4">
                    <div
                        class="bg-blue-50 text-blue-600 w-12 h-12 rounded-lg flex items-center justify-center text-xl group-hover:scale-110 transition-transform">
                        <i class="fa-solid fa-pen-nib"></i>
                    </div>
                    <div>
                        <h4 class="font-bold text-slate-800">Draft New Data</h4>
                        <p class="text-sm text-slate-500">Share your impact data formatted as a blueprint.</p>
                    </div>
                </div>
            </a>
            <a href="profile.php"
                class="group block p-6 bg-white rounded-xl border border-slate-200 hover:border-purple-500 hover:shadow-md transition-all">
                <div class="flex items-center gap-4">
                    <div
                        class="bg-purple-50 text-purple-600 w-12 h-12 rounded-lg flex items-center justify-center text-xl group-hover:scale-110 transition-transform">
                        <i class="fa-solid fa-user-pen"></i>
                    </div>
                    <div>
                        <h4 class="font-bold text-slate-800">Update Profile</h4>
                        <p class="text-sm text-slate-500">Manage your account details and public profile.</p>
                    </div>
                </div>
            </a>
            <a href="pricing.php"
                class="group block p-6 bg-white rounded-xl border border-slate-200 hover:border-green-500 hover:shadow-md transition-all">
                <div class="flex items-center gap-4">
                    <div
                        class="bg-green-50 text-green-600 w-12 h-12 rounded-lg flex items-center justify-center text-xl group-hover:scale-110 transition-transform">
                        <i class="fa-solid fa-credit-card"></i>
                    </div>
                    <div>
                        <h4 class="font-bold text-slate-800">Upgrade Plan</h4>
                        <p class="text-sm text-slate-500">Get more tokens and unlock premium features.</p>
                    </div>
                </div>
            </a>
        </div>

    </main>

    <?php include 'footer.php'; ?>

</body>

</html>