<?php
/**
 * Subscriber Dashboard
 * LandSales Pro - Main dashboard for land business management
 */
define('APP_RUNNING', true);
require_once '../db_connect.php';
require_once '../includes/auth.php';
require_once '../includes/subscription.php';
require_once '../includes/functions.php';
require_once '../includes/track.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];

// Get subscription info
$subscription = getActiveSubscription($userId);
$usageStats = getUsageStats($userId);

// Get dashboard stats
$totalProjects = db_fetch_one("SELECT COUNT(*) as count FROM projects WHERE user_id = ?", 'i', [$userId])['count'] ?? 0;
$totalPlots = db_fetch_one("SELECT COUNT(*) as count FROM plots WHERE user_id = ?", 'i', [$userId])['count'] ?? 0;
$availablePlots = db_fetch_one("SELECT COUNT(*) as count FROM plots WHERE user_id = ? AND status = 'available'", 'i', [$userId])['count'] ?? 0;
$soldPlots = db_fetch_one("SELECT COUNT(*) as count FROM plots WHERE user_id = ? AND status = 'sold'", 'i', [$userId])['count'] ?? 0;
$reservedPlots = db_fetch_one("SELECT COUNT(*) as count FROM plots WHERE user_id = ? AND status = 'reserved'", 'i', [$userId])['count'] ?? 0;

$totalBuyers = db_fetch_one("SELECT COUNT(*) as count FROM buyers WHERE user_id = ?", 'i', [$userId])['count'] ?? 0;
$totalSales = db_fetch_one("SELECT COUNT(*) as count FROM sales WHERE user_id = ?", 'i', [$userId])['count'] ?? 0;

// Revenue this month
$monthlyRevenue = db_fetch_one("SELECT COALESCE(SUM(amount), 0) as total FROM payments WHERE user_id = ? AND status = 'confirmed' AND MONTH(payment_date) = MONTH(CURRENT_DATE()) AND YEAR(payment_date) = YEAR(CURRENT_DATE())", 'i', [$userId])['total'] ?? 0;

// Pending payments
$pendingPayments = db_fetch_one("SELECT COALESCE(SUM(ps.amount - COALESCE(paid.total, 0)), 0) as total
    FROM payment_schedule ps
    JOIN sales s ON ps.sale_id = s.id
    LEFT JOIN (SELECT sale_id, SUM(amount) as total FROM payments WHERE status = 'confirmed' GROUP BY sale_id) paid ON ps.sale_id = paid.sale_id
    WHERE s.user_id = ? AND ps.due_date < CURDATE() AND ps.status != 'paid'", 'i', [$userId])['total'] ?? 0;

// Recent sales
$recentSales = db_fetch_all("SELECT s.*, b.full_name as buyer_name, p.plot_number, pr.name as project_name
    FROM sales s
    JOIN buyers b ON s.buyer_id = b.id
    JOIN plots p ON s.plot_id = p.id
    JOIN projects pr ON p.project_id = pr.id
    WHERE s.user_id = ?
    ORDER BY s.created_at DESC
    LIMIT 5", 'i', [$userId]);

// Recent payments
$recentPayments = db_fetch_all("SELECT pay.*, b.full_name as buyer_name, s.sale_number
    FROM payments pay
    JOIN sales s ON pay.sale_id = s.id
    JOIN buyers b ON s.buyer_id = b.id
    WHERE pay.user_id = ?
    ORDER BY pay.payment_date DESC
    LIMIT 5", 'i', [$userId]);

// Upcoming payments due
$upcomingDue = db_fetch_all("SELECT ps.*, s.sale_number, b.full_name as buyer_name, p.plot_number
    FROM payment_schedule ps
    JOIN sales s ON ps.sale_id = s.id
    JOIN buyers b ON s.buyer_id = b.id
    JOIN plots p ON s.plot_id = p.id
    WHERE s.user_id = ? AND ps.status = 'pending' AND ps.due_date >= CURDATE()
    ORDER BY ps.due_date ASC
    LIMIT 5", 'i', [$userId]);
?>
<!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 APP_NAME; ?></title>

    <!-- PWA Meta Tags -->
    <link rel="manifest" href="<?php echo SITE_URL; ?>/manifest.json">
    <meta name="theme-color" content="#667eea">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="LandSalesPro">
    <link rel="apple-touch-icon" href="<?php echo SITE_URL; ?>/assets/icons/icon-192x192.png">
    <meta name="description" content="Land Sales Management - Track your projects, plots, sales and payments">

    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/css/pwa.css">
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <div class="main-content">
        <?php
        $pageTitle = 'Dashboard';
        $headerActions = '<span class="welcome-text">Welcome, ' . htmlspecialchars($_SESSION['user_name'] ?? $_SESSION['full_name'] ?? 'User') . '!</span>';
        include 'includes/header.php';
        ?>

        <div class="content-wrapper">
            <!-- Stats Cards -->
            <div class="stats-grid">
                <div class="stat-card gradient-purple">
                    <div class="stat-icon">
                        <i class="fas fa-project-diagram"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value"><?php echo number_format($totalProjects); ?></div>
                        <div class="stat-label">Projects</div>
                    </div>
                </div>

                <div class="stat-card gradient-blue">
                    <div class="stat-icon">
                        <i class="fas fa-th"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value"><?php echo number_format($totalPlots); ?></div>
                        <div class="stat-label">Total Plots</div>
                    </div>
                </div>

                <div class="stat-card gradient-green">
                    <div class="stat-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value"><?php echo number_format($soldPlots); ?></div>
                        <div class="stat-label">Plots Sold</div>
                    </div>
                </div>

                <div class="stat-card gradient-orange">
                    <div class="stat-icon">
                        <i class="fas fa-money-bill-wave"></i>
                    </div>
                    <div class="stat-content">
                        <div class="stat-value">TZS <?php echo formatMoney($monthlyRevenue); ?></div>
                        <div class="stat-label">This Month</div>
                    </div>
                </div>
            </div>

            <!-- Plot Status Summary -->
            <div class="plot-summary">
                <div class="plot-stat available">
                    <div class="plot-count"><?php echo $availablePlots; ?></div>
                    <div class="plot-label">Available</div>
                </div>
                <div class="plot-stat reserved">
                    <div class="plot-count"><?php echo $reservedPlots; ?></div>
                    <div class="plot-label">Reserved</div>
                </div>
                <div class="plot-stat sold">
                    <div class="plot-count"><?php echo $soldPlots; ?></div>
                    <div class="plot-label">Sold</div>
                </div>
                <?php if ($pendingPayments > 0): ?>
                <div class="plot-stat overdue">
                    <div class="plot-count">TZS <?php echo formatMoney($pendingPayments); ?></div>
                    <div class="plot-label">Overdue</div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Main Grid -->
            <div class="dashboard-grid">
                <!-- Recent Sales -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-handshake"></i> Recent Sales</h3>
                        <a href="sales/" class="btn btn-sm btn-outline">View All</a>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recentSales)): ?>
                        <div class="empty-state">
                            <i class="fas fa-handshake"></i>
                            <p>No sales recorded yet</p>
                            <a href="sales/create.php" class="btn btn-primary btn-sm">Record First Sale</a>
                        </div>
                        <?php else: ?>
                        <div class="list-group">
                            <?php foreach ($recentSales as $sale): ?>
                            <div class="list-item">
                                <div class="list-icon">
                                    <i class="fas fa-receipt"></i>
                                </div>
                                <div class="list-content">
                                    <div class="list-title"><?php echo htmlspecialchars($sale['buyer_name']); ?></div>
                                    <div class="list-subtitle">
                                        <?php echo $sale['project_name']; ?> - Plot <?php echo $sale['plot_number']; ?>
                                    </div>
                                </div>
                                <div class="list-meta">
                                    <div class="list-amount">TZS <?php echo formatMoney($sale['total_price']); ?></div>
                                    <div class="list-date"><?php echo date('M j', strtotime($sale['sale_date'])); ?></div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Upcoming Payments -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-calendar-alt"></i> Upcoming Payments</h3>
                        <a href="payments/schedule.php" class="btn btn-sm btn-outline">View All</a>
                    </div>
                    <div class="card-body">
                        <?php if (empty($upcomingDue)): ?>
                        <div class="empty-state">
                            <i class="fas fa-calendar-check"></i>
                            <p>No upcoming payments</p>
                        </div>
                        <?php else: ?>
                        <div class="list-group">
                            <?php foreach ($upcomingDue as $due): ?>
                            <div class="list-item">
                                <div class="list-icon warning">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <div class="list-content">
                                    <div class="list-title"><?php echo htmlspecialchars($due['buyer_name']); ?></div>
                                    <div class="list-subtitle">Plot <?php echo $due['plot_number']; ?></div>
                                </div>
                                <div class="list-meta">
                                    <div class="list-amount">TZS <?php echo formatMoney($due['amount']); ?></div>
                                    <div class="list-date <?php echo strtotime($due['due_date']) < strtotime('+3 days') ? 'text-warning' : ''; ?>">
                                        <?php echo date('M j', strtotime($due['due_date'])); ?>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Recent Payments -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-money-bill-wave"></i> Recent Payments</h3>
                        <a href="payments/" class="btn btn-sm btn-outline">View All</a>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recentPayments)): ?>
                        <div class="empty-state">
                            <i class="fas fa-money-bill-wave"></i>
                            <p>No payments received yet</p>
                        </div>
                        <?php else: ?>
                        <div class="list-group">
                            <?php foreach ($recentPayments as $payment): ?>
                            <div class="list-item">
                                <div class="list-icon success">
                                    <i class="fas fa-check"></i>
                                </div>
                                <div class="list-content">
                                    <div class="list-title"><?php echo htmlspecialchars($payment['buyer_name']); ?></div>
                                    <div class="list-subtitle"><?php echo $payment['sale_number']; ?></div>
                                </div>
                                <div class="list-meta">
                                    <div class="list-amount text-success">+TZS <?php echo formatMoney($payment['amount']); ?></div>
                                    <div class="list-date"><?php echo date('M j', strtotime($payment['payment_date'])); ?></div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Quick Actions -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-bolt"></i> Quick Actions</h3>
                    </div>
                    <div class="card-body">
                        <div class="quick-actions">
                            <a href="projects/create.php" class="quick-action">
                                <i class="fas fa-plus-circle"></i>
                                <span>New Project</span>
                            </a>
                            <a href="plots/create.php" class="quick-action">
                                <i class="fas fa-th-large"></i>
                                <span>Add Plots</span>
                            </a>
                            <a href="buyers/create.php" class="quick-action">
                                <i class="fas fa-user-plus"></i>
                                <span>Add Buyer</span>
                            </a>
                            <a href="sales/create.php" class="quick-action">
                                <i class="fas fa-handshake"></i>
                                <span>Record Sale</span>
                            </a>
                            <a href="payments/create.php" class="quick-action">
                                <i class="fas fa-money-bill-wave"></i>
                                <span>Record Payment</span>
                            </a>
                            <a href="plots/grid.php" class="quick-action">
                                <i class="fas fa-border-all"></i>
                                <span>Plot Grid</span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Subscription Usage -->
            <?php if ($usageStats): ?>
            <div class="usage-card">
                <div class="card-header">
                    <h3><i class="fas fa-chart-pie"></i> Plan Usage</h3>
                    <span class="plan-name"><?php echo $usageStats['plan']; ?></span>
                </div>
                <div class="card-body">
                    <div class="usage-grid">
                        <div class="usage-item">
                            <div class="usage-header">
                                <span>Projects</span>
                                <span><?php echo $usageStats['projects']['unlimited'] ? 'Unlimited' : $usageStats['projects']['current'] . '/' . $usageStats['projects']['limit']; ?></span>
                            </div>
                            <?php if (!$usageStats['projects']['unlimited']): ?>
                            <div class="usage-bar">
                                <div class="usage-fill" style="width: <?php echo min(100, ($usageStats['projects']['current'] / max(1, $usageStats['projects']['limit'])) * 100); ?>%"></div>
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="usage-item">
                            <div class="usage-header">
                                <span>Plots</span>
                                <span><?php echo $usageStats['plots']['unlimited'] ? 'Unlimited' : $usageStats['plots']['current'] . '/' . $usageStats['plots']['limit']; ?></span>
                            </div>
                            <?php if (!$usageStats['plots']['unlimited']): ?>
                            <div class="usage-bar">
                                <div class="usage-fill" style="width: <?php echo min(100, ($usageStats['plots']['current'] / max(1, $usageStats['plots']['limit'])) * 100); ?>%"></div>
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="usage-item">
                            <div class="usage-header">
                                <span>Agents</span>
                                <span><?php echo $usageStats['agents']['unlimited'] ? 'Unlimited' : $usageStats['agents']['current'] . '/' . $usageStats['agents']['limit']; ?></span>
                            </div>
                            <?php if (!$usageStats['agents']['unlimited']): ?>
                            <div class="usage-bar">
                                <div class="usage-fill" style="width: <?php echo min(100, ($usageStats['agents']['current'] / max(1, $usageStats['agents']['limit'])) * 100); ?>%"></div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            margin: 0;
            background: #f1f5f9;
        }

        .welcome-text {
            color: #64748b;
            font-size: 0.9rem;
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 1.25rem;
            margin-bottom: 1.5rem;
        }

        .stat-card {
            border-radius: 14px;
            padding: 1.25rem;
            color: white;
            display: flex;
            align-items: center;
            gap: 1rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .gradient-purple { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .gradient-green { background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); }
        .gradient-blue { background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); }
        .gradient-orange { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }

        .stat-icon {
            width: 50px;
            height: 50px;
            background: rgba(255,255,255,0.2);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
        }

        .stat-value { font-size: 1.5rem; font-weight: 700; }
        .stat-label { font-size: 0.8rem; opacity: 0.9; }

        /* Plot Summary */
        .plot-summary {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
            flex-wrap: wrap;
        }

        .plot-stat {
            flex: 1;
            min-width: 120px;
            background: white;
            border-radius: 10px;
            padding: 1rem;
            text-align: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .plot-stat.available { border-left: 4px solid #22c55e; }
        .plot-stat.reserved { border-left: 4px solid #f59e0b; }
        .plot-stat.sold { border-left: 4px solid #ef4444; }
        .plot-stat.overdue { border-left: 4px solid #dc2626; }

        .plot-count { font-size: 1.5rem; font-weight: 700; color: #1e293b; }
        .plot-label { font-size: 0.8rem; color: #64748b; }

        /* Dashboard Grid */
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1.5rem;
            margin-bottom: 1.5rem;
        }

        /* Card */
        .card, .usage-card {
            background: white;
            border-radius: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            overflow: hidden;
        }

        .card-header {
            padding: 1rem 1.25rem;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            font-size: 0.95rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .card-header h3 i { color: #667eea; }

        .card-body { padding: 1rem 1.25rem; }

        /* Buttons */
        .btn {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 0.8rem;
        }

        .btn-sm { padding: 0.375rem 0.75rem; font-size: 0.75rem; }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-outline {
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
        }

        .btn-outline:hover { border-color: #667eea; color: #667eea; }

        /* List Group */
        .list-group { display: flex; flex-direction: column; }

        .list-item {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.65rem 0;
            border-bottom: 1px solid #f1f5f9;
        }

        .list-item:last-child { border-bottom: none; }

        .list-icon {
            width: 36px;
            height: 36px;
            border-radius: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8rem;
        }

        .list-icon.warning { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }
        .list-icon.success { background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); }

        .list-content { flex: 1; min-width: 0; }
        .list-title { font-weight: 500; color: #1e293b; font-size: 0.9rem; }
        .list-subtitle { font-size: 0.75rem; color: #64748b; }

        .list-meta { text-align: right; }
        .list-amount { font-weight: 600; font-size: 0.85rem; color: #1e293b; }
        .list-date { font-size: 0.75rem; color: #94a3b8; }

        .text-success { color: #16a34a; }
        .text-warning { color: #d97706; }

        /* Empty State */
        .empty-state {
            padding: 2rem;
            text-align: center;
            color: #94a3b8;
        }

        .empty-state i { font-size: 2rem; margin-bottom: 0.5rem; }
        .empty-state p { margin-bottom: 0.75rem; }

        /* Quick Actions */
        .quick-actions {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 0.75rem;
        }

        .quick-action {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.5rem;
            padding: 1rem 0.5rem;
            background: #f8fafc;
            border-radius: 10px;
            text-decoration: none;
            color: #1e293b;
            font-size: 0.8rem;
            font-weight: 500;
            transition: all 0.2s;
        }

        .quick-action:hover {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            transform: translateY(-2px);
        }

        .quick-action i { font-size: 1.25rem; }

        /* Usage Card */
        .usage-card .plan-name {
            font-size: 0.8rem;
            font-weight: 600;
            color: #667eea;
            background: rgba(102, 126, 234, 0.1);
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
        }

        .usage-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1.5rem;
        }

        .usage-item { }

        .usage-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
            font-size: 0.85rem;
        }

        .usage-header span:first-child { color: #64748b; }
        .usage-header span:last-child { font-weight: 600; color: #1e293b; }

        .usage-bar {
            height: 6px;
            background: #e2e8f0;
            border-radius: 3px;
            overflow: hidden;
        }

        .usage-fill {
            height: 100%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 3px;
        }

        /* Responsive */
        @media (max-width: 992px) {
            .dashboard-grid { grid-template-columns: 1fr; }
            .stats-grid { grid-template-columns: repeat(2, 1fr); }
            .usage-grid { grid-template-columns: 1fr; gap: 1rem; }
        }

        @media (max-width: 576px) {
            .stats-grid { grid-template-columns: 1fr; }
            .quick-actions { grid-template-columns: repeat(2, 1fr); }
            .plot-summary { flex-direction: column; }
        }
    </style>

    <!-- PWA Scripts -->
    <script src="<?php echo SITE_URL; ?>/assets/js/offline-db.js"></script>
    <script src="<?php echo SITE_URL; ?>/assets/js/pwa.js"></script>
</body>
</html>
