<?php 
include 'config.php'; 
if(!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }

// Simple logic to count days remaining
$today = new DateTime();
$expiry = new DateTime(defined('EXPIRY_DATE_LIVE') ? EXPIRY_DATE_LIVE : 'now');
$interval = $today->diff($expiry);
$days_left = $interval->format('%r%a');

$agency_id = $_SESSION['agency_id'];
$today = date('Y-m-d');

// 1. Count Queries Today
$q_today = $conn->query("SELECT COUNT(id) as total FROM queries WHERE agency_id = $agency_id AND DATE(created_at) = '$today'")->fetch_assoc()['total'];

// 2. Count Total Clients
$total_clients = $conn->query("SELECT COUNT(id) as total FROM clients WHERE agency_id = $agency_id")->fetch_assoc()['total'];

// 3. Count Total Vouchers (Umrah + Tickets)
$umrah_count = $conn->query("SELECT COUNT(id) as total FROM umrah_vouchers WHERE agency_id = $agency_id")->fetch_assoc()['total'];
$ticket_count = $conn->query("SELECT COUNT(id) as total FROM ticket_vouchers WHERE agency_id = $agency_id")->fetch_assoc()['total'];
$total_vouchers = $umrah_count + $ticket_count;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard | <?php echo AGENCY_NAME_LIVE; ?></title>
    <!-- Google Fonts & Icons -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        :root {
            --primary: #4e73df;
            --secondary: #1e293b;
            --success: #1cc88a;
            --bg-color: #f8f9fc;
            --sidebar-width: 260px;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        body { background-color: var(--bg-color); display: flex; }

        /* Sidebar Styling */
        .sidebar {
    width: var(--sidebar-width);
    background: var(--secondary);
    height: 100vh;
    position: fixed;
    color: #fff;
    padding: 20px 0;

    display: flex;
    flex-direction: column;
    overflow-y: auto;   /* 🔥 THIS FIXES OVERLAP */
}

        .sidebar-brand {
            padding: 0 25px 30px;
            font-size: 20px;
            font-weight: 600;
            display: flex;
            align-items: center;
            color: #fff;
            text-decoration: none;
        }
        .sidebar-brand i { margin-right: 10px; color: var(--primary); }

        .nav-menu {
    list-style: none;
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
}

        .nav-item {
    padding: 0 20px;
    margin-bottom: 5px;
}

        .nav-link {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            color: rgba(255,255,255,0.7);
            text-decoration: none;
            border-radius: 8px;
            transition: 0.3s;
        }
        .nav-link i { width: 25px; font-size: 18px; }
        .nav-link:hover, .nav-link.active {
            background: rgba(255,255,255,0.1);
            color: #fff;
        }
        .admin-section {
            margin-top: 30px;
            padding: 0 20px;
            font-size: 11px;
            text-transform: uppercase;
            color: rgba(255,255,255,0.4);
            letter-spacing: 1px;
        }

        /* Main Content */
        .main-content {
            margin-left: var(--sidebar-width);
            width: calc(100% - var(--sidebar-width));
            padding: 30px;
        }

        /* Top Bar */
        .top-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
        }
        .user-info { display: flex; align-items: center; gap: 15px; }
        .user-name { font-weight: 500; color: var(--secondary); }
        .avatar { width: 40px; height: 40px; background: var(--primary); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: #fff;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.02);
            border-left: 5px solid var(--primary);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .stat-val { font-size: 24px; font-weight: 600; color: var(--secondary); }
        .stat-label { font-size: 13px; color: #64748b; text-transform: uppercase; }
        .stat-icon { font-size: 30px; color: rgba(0,0,0,0.1); }

        /* Welcome Section */
        .welcome-card {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            padding: 40px;
            border-radius: 15px;
            margin-bottom: 30px;
            position: relative;
            overflow: hidden;
        }
        .welcome-card h2 { font-size: 28px; margin-bottom: 10px; }
        .welcome-card p { opacity: 0.9; }
        .welcome-card img { position: absolute; right: -20px; bottom: -20px; width: 200px; opacity: 0.2; }

    </style>
</head>
<body>

    <!-- Sidebar -->
    <div class="sidebar">
        <a href="#" class="sidebar-brand">
            <i class="fas fa-plane-departure"></i>
            <span>TRAVEL SAAS</span>
        </a>
        
        <ul class="nav-menu">
    <?php if($_SESSION['user_role'] == 'SuperAdmin'): ?>
        <!-- SUPER ADMIN MENU -->
         <li class="nav-item"><a href="dashboard.php" class="nav-link active"><i class="fas fa-home"></i> Dashboard</a></li>
        <li class="nav-item"><a href="admin_dashboard.php" class="nav-link "><i class="fas fa-chart-line"></i> SaaS Overview</a></li>
        <li class="nav-item"><a href="manage_agencies.php" class="nav-link"><i class="fas fa-building"></i> Manage Agencies</a></li>
        <li class="nav-item"><a href="saas_revenue.php" class="nav-link"><i class="fas fa-file-invoice-dollar"></i> Revenue & Payments</a></li>
         <li class="nav-item"><a href="generate_invoice.php" class="nav-link" style="color: #1cc88a;"><i class="fas fa-file-invoice-dollar"></i> Generate New Bill</a></li>
         <li class="nav-item"><a href="admin_group_tickets.php" class="nav-link" style="color: #3498db;"><i class="fas fa-plane-arrival"></i> B2B Group Inventory</a></li>
    <li class="nav-item"><a href="broadcast.php" class="nav-link"><i class="fas fa-bullhorn"></i> Send Announcements</a></li>
    <li class="nav-item"><a href="profile.php" class="nav-link"><i class="fas fa-user-shield"></i> My Profile</a></li>
    <?php else: ?>
        <!-- AGENCY MENU -->
        <li class="nav-item"><a href="dashboard.php" class="nav-link active"><i class="fas fa-home"></i> Dashboard</a></li>
        <li class="nav-item"><a href="clients.php" class="nav-link"><i class="fas fa-users"></i> My Clients</a></li>
        <li class="nav-item"><a href="queries.php" class="nav-link"><i class="fas fa-question-circle"></i> Enquiries</a></li>
        <?php if($_SESSION['user_role'] == 'AgencyOwner'): ?>
    <li class="nav-item"><a href="staff.php" class="nav-link"><i class="fas fa-user-tie"></i> Manage Staff</a></li>
<?php endif; ?>
        <li class="nav-item"><a href="marketplace.php" class="nav-link" style="background: rgba(28, 200, 138, 0.1); color: #1cc88a;"><i class="fas fa-shopping-cart"></i> B2B Marketplace</a></li>
        <li class="nav-item"><a href="umrah_vouchers.php" class="nav-link"><i class="fas fa-kaaba"></i> Umrah Vouchers</a></li>
        <li class="nav-item"><a href="ticket_vouchers.php" class="nav-link"><i class="fas fa-ticket-alt"></i> Ticket Vouchers</a></li>
        <li class="nav-item"><a href="posters.php" class="nav-link"><i class="fas fa-image"></i> Poster Maker</a></li>
        <li class="nav-item"><a href="ledger.php" class="nav-link"><i class="fas fa-wallet"></i> Clients Account</a></li>
        <li class="nav-item">
    <a href="agency_profile.php" class="nav-link" style="background: rgba(78, 115, 223, 0.1); color: #4e73df;">
        <i class="fas fa-cog"></i> Agency Settings
    </a>
</li>
    <?php endif; ?>
</ul>

        <?php if($_SESSION['user_role'] == 'SuperAdmin'): ?>

        <?php endif; ?>

        <div style="position: absolute; bottom: 20px; width: 100%;">
            <li class="nav-item" style="list-style: none;"><a href="logout.php" class="nav-link" style="color: #ff7675;"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- UPDATED TOP BAR FOR dashboard.php -->
<div class="top-bar" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px;">
    <h1>Overview</h1>
    
    <div style="display: flex; align-items: center; gap: 20px;">
    <!-- SaaS BILLING WIDGET -->
    <?php 
        $aid = $_SESSION['agency_id'];
        $agency_res = $conn->query("SELECT balance_due FROM agencies WHERE id = $aid");
        $agency_data = $agency_res->fetch_assoc();
        $bal = $agency_data['balance_due'];
    ?>
    <div style="display: flex; align-items: center; gap: 10px;">
        <!-- Balance Info -->
        <div style="background: #fff; padding: 10px 20px; border-radius: 12px; border: 1px solid <?php echo ($bal > 0 ? '#feb2b2' : '#e2e8f0'); ?>; display: flex; align-items: center; gap: 10px;">
            <i class="fas fa-wallet" style="color: <?php echo ($bal > 0 ? '#e74a3b' : '#1cc88a'); ?>;"></i>
            <div>
                <small style="display:block; font-size: 10px; color: #64748b; text-transform: uppercase;">Software Balance</small>
                <b style="color: <?php echo ($bal > 0 ? '#e74a3b' : '#333'); ?>;">PKR <?php echo number_format($bal); ?></b>
            </div>
        </div>
        <!-- History Button -->
        <a href="subscription_history.php" title="View Payment History" style="background: #f1f5f9; color: #475569; width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; text-decoration: none; border: 1px solid #e2e8f0;">
            <i class="fas fa-history"></i>
        </a>
    </div>


        <div class="user-info" style="display: flex; align-items: center; gap: 15px;">
            <div style="text-align: right;">
                <div class="user-name" style="font-weight: 600;"><?php echo $_SESSION['user_name']; ?></div>
                <small style="color: #64748b;"><?php echo AGENCY_NAME_LIVE; ?></small>
            </div>
            <div class="avatar" style="width: 40px; height: 40px; background: var(--primary); border-radius: 50%; color: white; display: flex; align-items: center; justify-content: center; font-weight: 600;">
                <?php echo substr($_SESSION['user_name'], 0, 1); ?>
            </div>
        </div>
    </div>
</div>

        <div class="welcome-card">
            <h2>Assalam-o-Alaikum, <?php echo $_SESSION['user_name']; ?>!</h2>
            <p>Welcome to your professional travel agency command center. Ready to make some bookings?</p>
            <i class="fas fa-mosque" style="position: absolute; right: 30px; top: 30px; font-size: 100px; opacity: 0.1;"></i>
        </div>
        <?php if($_SESSION['user_role'] != 'SuperAdmin' && $agency['balance_due'] > 0): ?>
    <div style="background: #fff5f5; border: 1px solid #feb2b2; padding: 15px; border-radius: 12px; margin-bottom: 25px; display: flex; justify-content: space-between; align-items: center;">
        <div>
            <h4 style="color: #c53030; margin: 0;"><i class="fas fa-exclamation-circle"></i> Outstanding Balance Due</h4>
            <p style="color: #742a2a; font-size: 14px; margin: 0;">You have a pending amount of <b>PKR <?php echo number_format($agency['balance_due']); ?></b> for your software subscription.</p>
        </div>
        <a href="payment_info.php" style="background: #c53030; color: white; padding: 8px 15px; border-radius: 6px; text-decoration: none; font-weight: 600; font-size: 13px;">Pay Now</a>
    </div>
<?php endif; ?>
        <!-- Announcement Section -->
<?php 
$news = $conn->query("SELECT * FROM announcements ORDER BY id DESC LIMIT 1");
if($news->num_rows > 0): 
    $item = $news->fetch_assoc();
?>
<div style="background: #fff3cd; border-left: 5px solid #ffc107; padding: 15px; border-radius: 8px; margin-bottom: 30px;">
    <h4 style="color: #856404;"><i class="fas fa-bullhorn"></i> <?php echo $item['title']; ?></h4>
    <p style="font-size: 14px; color: #856404;"><?php echo $item['message']; ?></p>
</div>
<?php endif; ?>

        <div class="stats-grid">
            <div class="stat-card">
                <div>
                    <div class="stat-label">Subscription Status</div>
                    <div class="stat-val" style="color: var(--success);"><?php echo AGENCY_STATUS_LIVE; ?></div>
                </div>
                <i class="fas fa-check-circle stat-icon"></i>
            </div>
            <div class="stat-card" style="border-left-color: #f6c23e;">
                <div>
                    <div class="stat-label">Days Remaining</div>
                    <div class="stat-val"><?php echo $days_left; ?> Days</div>
                </div>
                <i class="fas fa-clock stat-icon"></i>
            </div>
            <div class="stat-card" style="border-left-color: #36b9cc;">
                <div>
                    <div class="stat-label">Queries Today</div>
                    <div class="stat-val">0</div>
                </div>
                <i class="fas fa-comments stat-icon"></i>
            </div>
        </div>

        <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 25px; margin-top: 30px;">
    
    <!-- LEFT SIDE: RECENT ACTIVITY -->
    <div style="background: #fff; padding: 25px; border-radius: 15px; box-shadow: 0 4px 6px rgba(0,0,0,0.02);">
    <h3 style="margin-bottom: 20px; font-size: 18px; color: var(--secondary);"><i class="fas fa-history"></i> Recent Activity</h3>
    
    <?php
    // IMPROVED QUERY: Fetching voucher_data and using LEFT JOIN for registered clients
    $act_sql = "(SELECT 'client' as type, name as db_name, '' as v_data, created_at FROM clients WHERE agency_id = $agency_id)
                UNION
                (SELECT 'umrah' as type, c.name as db_name, v.voucher_data as v_data, v.created_at FROM umrah_vouchers v LEFT JOIN clients c ON v.client_id = c.id WHERE v.agency_id = $agency_id)
                UNION
                (SELECT 'ticket' as type, c.name as db_name, t.voucher_data as v_data, t.created_at FROM ticket_vouchers t LEFT JOIN clients c ON t.client_id = c.id WHERE t.agency_id = $agency_id)
                ORDER BY created_at DESC LIMIT 5";

    $activities = $conn->query($act_sql);

    if($activities->num_rows > 0):
        while($act = $activities->fetch_assoc()):
            // 1. Determine the Icon and Color
            $icon = "fa-user-plus"; $color = "#4e73df"; // Default for Client
            $type_label = "Registration";

            if($act['type'] == 'umrah') { 
                $icon = "fa-kaaba"; $color = "#1cc88a"; $type_label = "Umrah Voucher"; 
            }
            if($act['type'] == 'ticket') { 
                $icon = "fa-ticket-alt"; $color = "#36b9cc"; $type_label = "Ticket Quote"; 
            }

            // 2. Logic to find the Client Name (DB or Manual JSON)
            $client_name = "Guest";
            if(!empty($act['db_name'])) {
                $client_name = $act['db_name'];
            } elseif(!empty($act['v_data'])) {
                $json = json_decode($act['v_data'], true);
                // Look for manual name in JSON (matches our voucher handler)
                $client_name = $json['client_display_name'] ?? "Unknown Client";
            }

            // 3. Construct the Title
            if($act['type'] == 'client') {
                $display_title = "New Client Added: <b>$client_name</b>";
            } else {
                $display_title = "$type_label for <b>$client_name</b>";
            }
    ?>
        <div style="display: flex; align-items: center; padding: 15px; border-bottom: 1px solid #f8f9fc;">
            <!-- Icon Box -->
            <div style="width: 42px; height: 42px; border-radius: 12px; background: <?php echo $color; ?>15; color: <?php echo $color; ?>; display: flex; align-items: center; justify-content: center; margin-right: 15px; font-size: 18px;">
                <i class="fas <?php echo $icon; ?>"></i>
            </div>
            
            <!-- Details -->
            <div style="flex: 1;">
                <div style="font-size: 14px; color: #334155;"><?php echo $display_title; ?></div>
                <div style="font-size: 11px; color: #94a3b8; margin-top: 2px;">
                    <i class="far fa-clock"></i> <?php echo date('d M Y | h:i A', strtotime($act['created_at'])); ?>
                </div>
            </div>

            <!-- Status Tag -->
            <div style="font-size: 10px; color: #1cc88a; background: #dcfce7; padding: 3px 8px; border-radius: 4px; font-weight: 700; text-transform: uppercase;">
                Success
            </div>
        </div>
    <?php endwhile; else: ?>
        <div style="text-align: center; padding: 40px; color: #94a3b8;">
            <i class="fas fa-history" style="font-size: 40px; margin-bottom: 10px; opacity: 0.2;"></i>
            <p>No activity recorded yet.</p>
        </div>
    <?php endif; ?>
</div>

    <!-- RIGHT SIDE: QUICK STATS -->
    <div style="background: #fff; padding: 25px; border-radius: 15px; box-shadow: 0 4px 6px rgba(0,0,0,0.02);">
        <h3 style="margin-bottom: 20px; font-size: 18px; color: var(--secondary);">Quick Summary</h3>
        
        <div style="margin-bottom: 20px;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                <span style="font-size: 13px; color: #64748b;">Total Clients</span>
                <span style="font-weight: 600;"><?php echo $total_clients; ?></span>
            </div>
            <div style="height: 8px; background: #f1f5f9; border-radius: 4px; overflow: hidden;">
                <div style="width: <?php echo min($total_clients, 100); ?>%; height: 100%; background: var(--primary);"></div>
            </div>
        </div>

        <div style="margin-bottom: 20px;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                <span style="font-size: 13px; color: #64748b;">Total Vouchers</span>
                <span style="font-weight: 600;"><?php echo $total_vouchers; ?></span>
            </div>
            <div style="height: 8px; background: #f1f5f9; border-radius: 4px; overflow: hidden;">
                <div style="width: <?php echo min($total_vouchers, 100); ?>%; height: 100%; background: var(--success);"></div>
            </div>
        </div>

        <a href="queries.php" style="display: block; text-align: center; padding: 12px; background: #f8f9fc; border-radius: 10px; color: var(--primary); text-decoration: none; font-size: 13px; font-weight: 600; margin-top: 30px;">
            View All Enquiries <i class="fas fa-arrow-right"></i>
        </a>
    </div>

</div>
        
    </div>

</body>
</html>