<?php
/**
 * Project Performance Report
 * LandSales Pro - Project-wise analysis
 */
define('APP_RUNNING', true);
require_once '../../db_connect.php';
require_once '../../includes/auth.php';
require_once '../../includes/subscription.php';
require_once '../../includes/functions.php';

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

$userId = $_SESSION['user_id'];

// Get all projects with stats
$projects = db_fetch_all("SELECT pr.*,
    (SELECT COUNT(*) FROM plots WHERE project_id = pr.id) as total_plots,
    (SELECT COUNT(*) FROM plots WHERE project_id = pr.id AND status = 'available') as available_plots,
    (SELECT COUNT(*) FROM plots WHERE project_id = pr.id AND status = 'reserved') as reserved_plots,
    (SELECT COUNT(*) FROM plots WHERE project_id = pr.id AND status = 'sold') as sold_plots,
    (SELECT COALESCE(SUM(s.total_price), 0) FROM sales s JOIN plots p ON s.plot_id = p.id WHERE p.project_id = pr.id AND s.status IN ('active', 'completed')) as total_sales_value,
    (SELECT COALESCE(SUM(py.amount), 0) FROM payments py JOIN sales s ON py.sale_id = s.id JOIN plots p ON s.plot_id = p.id WHERE p.project_id = pr.id AND py.status = 'confirmed') as total_collected
    FROM projects pr WHERE pr.user_id = ? ORDER BY pr.name", 'i', [$userId]);

// Calculate totals
$totalProjects = count($projects);
$totalPlots = array_sum(array_column($projects, 'total_plots'));
$totalSold = array_sum(array_column($projects, 'sold_plots'));
$totalValue = array_sum(array_column($projects, 'total_sales_value'));
$totalCollected = array_sum(array_column($projects, 'total_collected'));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Project Performance - <?php echo APP_NAME; ?></title>
    <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">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Project Performance</h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <button onclick="window.print()" class="btn btn-outline">
                    <i class="fas fa-print"></i> Print
                </button>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Summary Stats -->
            <div class="stats-row">
                <div class="stat-mini">
                    <i class="fas fa-building"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($totalProjects); ?></div>
                        <div class="stat-label">Projects</div>
                    </div>
                </div>
                <div class="stat-mini info">
                    <i class="fas fa-th"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($totalPlots); ?></div>
                        <div class="stat-label">Total Plots</div>
                    </div>
                </div>
                <div class="stat-mini success">
                    <i class="fas fa-check-circle"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($totalSold); ?></div>
                        <div class="stat-label">Plots Sold</div>
                    </div>
                </div>
                <div class="stat-mini warning">
                    <i class="fas fa-chart-line"></i>
                    <div>
                        <div class="stat-value">TZS <?php echo formatMoney($totalValue); ?></div>
                        <div class="stat-label">Sales Value</div>
                    </div>
                </div>
            </div>

            <!-- Project Cards -->
            <div class="projects-grid">
                <?php foreach ($projects as $project):
                    $soldPercent = $project['total_plots'] > 0 ? ($project['sold_plots'] / $project['total_plots']) * 100 : 0;
                    $collectionPercent = $project['total_sales_value'] > 0 ? ($project['total_collected'] / $project['total_sales_value']) * 100 : 0;
                    $balance = $project['total_sales_value'] - $project['total_collected'];
                ?>
                <div class="project-card">
                    <div class="project-header">
                        <h3><?php echo htmlspecialchars($project['name']); ?></h3>
                        <span class="project-location"><?php echo htmlspecialchars($project['location'] ?? 'No location'); ?></span>
                    </div>

                    <div class="project-body">
                        <div class="plot-distribution">
                            <h4>Plot Status</h4>
                            <div class="distribution-bar">
                                <?php if ($project['total_plots'] > 0): ?>
                                <div class="bar-segment available" style="width: <?php echo ($project['available_plots'] / $project['total_plots']) * 100; ?>%" title="Available: <?php echo $project['available_plots']; ?>"></div>
                                <div class="bar-segment reserved" style="width: <?php echo ($project['reserved_plots'] / $project['total_plots']) * 100; ?>%" title="Reserved: <?php echo $project['reserved_plots']; ?>"></div>
                                <div class="bar-segment sold" style="width: <?php echo ($project['sold_plots'] / $project['total_plots']) * 100; ?>%" title="Sold: <?php echo $project['sold_plots']; ?>"></div>
                                <?php else: ?>
                                <div class="bar-segment empty" style="width: 100%"></div>
                                <?php endif; ?>
                            </div>
                            <div class="distribution-legend">
                                <span class="legend-item available"><span class="dot"></span> Available: <?php echo $project['available_plots']; ?></span>
                                <span class="legend-item reserved"><span class="dot"></span> Reserved: <?php echo $project['reserved_plots']; ?></span>
                                <span class="legend-item sold"><span class="dot"></span> Sold: <?php echo $project['sold_plots']; ?></span>
                            </div>
                        </div>

                        <div class="financial-summary">
                            <div class="summary-item">
                                <span class="summary-label">Total Plots</span>
                                <span class="summary-value"><?php echo $project['total_plots']; ?></span>
                            </div>
                            <div class="summary-item">
                                <span class="summary-label">Sales Value</span>
                                <span class="summary-value">TZS <?php echo formatMoney($project['total_sales_value']); ?></span>
                            </div>
                            <div class="summary-item">
                                <span class="summary-label">Collected</span>
                                <span class="summary-value text-success">TZS <?php echo formatMoney($project['total_collected']); ?></span>
                            </div>
                            <div class="summary-item">
                                <span class="summary-label">Balance</span>
                                <span class="summary-value <?php echo $balance > 0 ? 'text-warning' : 'text-success'; ?>">TZS <?php echo formatMoney($balance); ?></span>
                            </div>
                        </div>

                        <div class="progress-section">
                            <div class="progress-item">
                                <div class="progress-header">
                                    <span>Sales Progress</span>
                                    <span><?php echo round($soldPercent); ?>%</span>
                                </div>
                                <div class="progress-bar">
                                    <div class="progress-fill sold" style="width: <?php echo $soldPercent; ?>%"></div>
                                </div>
                            </div>
                            <div class="progress-item">
                                <div class="progress-header">
                                    <span>Collection Progress</span>
                                    <span><?php echo round($collectionPercent); ?>%</span>
                                </div>
                                <div class="progress-bar">
                                    <div class="progress-fill collected" style="width: <?php echo $collectionPercent; ?>%"></div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="project-footer">
                        <a href="../plots/grid.php?project=<?php echo $project['id']; ?>" class="btn btn-outline btn-sm">
                            <i class="fas fa-th"></i> View Grid
                        </a>
                        <a href="../projects/view.php?id=<?php echo $project['id']; ?>" class="btn btn-primary btn-sm">
                            <i class="fas fa-eye"></i> Details
                        </a>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <?php if (empty($projects)): ?>
            <div class="card">
                <div class="empty-state">
                    <i class="fas fa-building"></i>
                    <h3>No Projects Yet</h3>
                    <p>Create your first project to start tracking performance.</p>
                    <a href="../projects/create.php" class="btn btn-primary">Create Project</a>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; 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.875rem; }
        .btn-sm { padding: 0.5rem 0.75rem; font-size: 0.8rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .stats-row { display: flex; gap: 1rem; margin-bottom: 1.5rem; flex-wrap: wrap; }
        .stat-mini { flex: 1; min-width: 180px; padding: 1rem; background: white; border-radius: 10px; display: flex; align-items: center; gap: 0.75rem; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .stat-mini i { width: 40px; height: 40px; background: #f1f5f9; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: #64748b; }
        .stat-mini.success { border-left: 3px solid #22c55e; }
        .stat-mini.success i { background: #dcfce7; color: #16a34a; }
        .stat-mini.info { border-left: 3px solid #3b82f6; }
        .stat-mini.info i { background: #dbeafe; color: #2563eb; }
        .stat-mini.warning { border-left: 3px solid #f59e0b; }
        .stat-mini.warning i { background: #fef3c7; color: #d97706; }
        .stat-mini .stat-value { font-size: 1.1rem; font-weight: 700; color: #1e293b; }
        .stat-mini .stat-label { font-size: 0.75rem; color: #64748b; }

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

        .project-card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .project-header { padding: 1.25rem; border-bottom: 1px solid #f1f5f9; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .project-header h3 { margin: 0 0 0.25rem; font-size: 1.1rem; }
        .project-location { font-size: 0.85rem; opacity: 0.9; }

        .project-body { padding: 1.25rem; }

        .plot-distribution h4 { font-size: 0.85rem; color: #64748b; margin: 0 0 0.5rem; }
        .distribution-bar { height: 12px; background: #e2e8f0; border-radius: 6px; overflow: hidden; display: flex; margin-bottom: 0.5rem; }
        .bar-segment { height: 100%; }
        .bar-segment.available { background: #22c55e; }
        .bar-segment.reserved { background: #f59e0b; }
        .bar-segment.sold { background: #ef4444; }
        .bar-segment.empty { background: #e2e8f0; }

        .distribution-legend { display: flex; gap: 1rem; font-size: 0.75rem; flex-wrap: wrap; }
        .legend-item { display: flex; align-items: center; gap: 0.25rem; color: #64748b; }
        .legend-item .dot { width: 8px; height: 8px; border-radius: 50%; }
        .legend-item.available .dot { background: #22c55e; }
        .legend-item.reserved .dot { background: #f59e0b; }
        .legend-item.sold .dot { background: #ef4444; }

        .financial-summary { display: grid; grid-template-columns: repeat(2, 1fr); gap: 0.75rem; margin: 1rem 0; padding: 1rem; background: #f8fafc; border-radius: 10px; }
        .summary-item { }
        .summary-label { display: block; font-size: 0.7rem; color: #64748b; text-transform: uppercase; }
        .summary-value { font-weight: 600; color: #1e293b; font-size: 0.9rem; }
        .text-success { color: #16a34a; }
        .text-warning { color: #d97706; }

        .progress-section { }
        .progress-item { margin-bottom: 0.75rem; }
        .progress-header { display: flex; justify-content: space-between; font-size: 0.8rem; margin-bottom: 0.25rem; }
        .progress-bar { height: 6px; background: #e2e8f0; border-radius: 3px; overflow: hidden; }
        .progress-fill { height: 100%; border-radius: 3px; }
        .progress-fill.sold { background: #ef4444; }
        .progress-fill.collected { background: #22c55e; }

        .project-footer { padding: 1rem 1.25rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: flex-end; gap: 0.5rem; }

        .card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .empty-state { text-align: center; padding: 3rem; }
        .empty-state i { font-size: 3rem; color: #94a3b8; margin-bottom: 1rem; }
        .empty-state h3 { margin: 0 0 0.5rem; color: #1e293b; }
        .empty-state p { margin: 0 0 1rem; color: #64748b; }

        @media print {
            body { background: white; }
            .header-actions { display: none; }
            .sidebar, .top-header { display: none; }
            .main-content { margin-left: 0; padding: 0; }
            .project-card { box-shadow: none; border: 1px solid #e2e8f0; break-inside: avoid; }
            .project-footer { display: none; }
        }

        @media (max-width: 992px) {
            .projects-grid { grid-template-columns: 1fr; }
        }

        @media (max-width: 768px) {
            .stats-row { flex-direction: column; }
            .financial-summary { grid-template-columns: 1fr; }
        }
    </style>
</body>
</html>
