<?php
/**
 * View Project
 * LandSales Pro - Project details and statistics
 */
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'];
$projectId = intval($_GET['id'] ?? 0);

// Get project
$project = db_fetch_one("SELECT * FROM projects WHERE id = ? AND user_id = ?", 'ii', [$projectId, $userId]);

if (!$project) {
    header('Location: index.php');
    exit;
}

// Get plot statistics
$plotStats = db_fetch_one("SELECT
    COUNT(*) as total,
    SUM(CASE WHEN status = 'available' THEN 1 ELSE 0 END) as available,
    SUM(CASE WHEN status = 'reserved' THEN 1 ELSE 0 END) as reserved,
    SUM(CASE WHEN status = 'sold' THEN 1 ELSE 0 END) as sold,
    COALESCE(SUM(price), 0) as total_value,
    COALESCE(SUM(CASE WHEN status = 'sold' THEN price ELSE 0 END), 0) as sold_value
    FROM plots WHERE project_id = ?", 'i', [$projectId]);

// Get sales statistics
$salesStats = db_fetch_one("SELECT
    COUNT(*) as total_sales,
    COALESCE(SUM(total_price), 0) as total_sales_value,
    COALESCE(SUM(deposit_amount), 0) as total_deposits
    FROM sales s
    JOIN plots p ON s.plot_id = p.id
    WHERE p.project_id = ? AND s.status IN ('active', 'completed')", 'i', [$projectId]);

// Get payment statistics
$paymentStats = db_fetch_one("SELECT
    COALESCE(SUM(py.amount), 0) as total_collected
    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 = ? AND py.status = 'confirmed'", 'i', [$projectId]);

// Get recent plots
$recentPlots = db_fetch_all("SELECT * FROM plots WHERE project_id = ? ORDER BY created_at DESC LIMIT 10", 'i', [$projectId]);

// Get recent sales
$recentSales = db_fetch_all("SELECT s.*, p.plot_number, b.full_name as buyer_name
    FROM sales s
    JOIN plots p ON s.plot_id = p.id
    JOIN buyers b ON s.buyer_id = b.id
    WHERE p.project_id = ?
    ORDER BY s.sale_date DESC LIMIT 5", 'i', [$projectId]);

$balance = ($salesStats['total_sales_value'] ?? 0) - ($paymentStats['total_collected'] ?? 0);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($project['name']); ?> - <?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"><?php echo htmlspecialchars($project['name']); ?></h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <a href="edit.php?id=<?php echo $projectId; ?>" class="btn btn-outline">
                    <i class="fas fa-edit"></i> Edit
                </a>
                <a href="../plots/grid.php?project=<?php echo $projectId; ?>" class="btn btn-primary">
                    <i class="fas fa-th"></i> View Grid
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Project Info -->
            <div class="project-header-card">
                <div class="project-info">
                    <div class="project-meta">
                        <?php if ($project['location']): ?>
                        <span><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($project['location']); ?></span>
                        <?php endif; ?>
                        <?php if ($project['total_area']): ?>
                        <span><i class="fas fa-ruler-combined"></i> <?php echo number_format($project['total_area']); ?> <?php echo $project['area_unit']; ?></span>
                        <?php endif; ?>
                        <span><i class="fas fa-calendar"></i> Created <?php echo date('M j, Y', strtotime($project['created_at'])); ?></span>
                    </div>
                    <?php if ($project['description']): ?>
                    <p class="project-desc"><?php echo nl2br(htmlspecialchars($project['description'])); ?></p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Stats Grid -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon blue"><i class="fas fa-th"></i></div>
                    <div class="stat-details">
                        <div class="stat-value"><?php echo number_format($plotStats['total'] ?? 0); ?></div>
                        <div class="stat-label">Total Plots</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon green"><i class="fas fa-check-circle"></i></div>
                    <div class="stat-details">
                        <div class="stat-value"><?php echo number_format($plotStats['available'] ?? 0); ?></div>
                        <div class="stat-label">Available</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon orange"><i class="fas fa-clock"></i></div>
                    <div class="stat-details">
                        <div class="stat-value"><?php echo number_format($plotStats['reserved'] ?? 0); ?></div>
                        <div class="stat-label">Reserved</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon red"><i class="fas fa-tag"></i></div>
                    <div class="stat-details">
                        <div class="stat-value"><?php echo number_format($plotStats['sold'] ?? 0); ?></div>
                        <div class="stat-label">Sold</div>
                    </div>
                </div>
            </div>

            <!-- Financial Stats -->
            <div class="financial-grid">
                <div class="financial-card">
                    <div class="financial-header">
                        <i class="fas fa-coins"></i>
                        <span>Total Plot Value</span>
                    </div>
                    <div class="financial-value">TZS <?php echo number_format($plotStats['total_value'] ?? 0); ?></div>
                </div>
                <div class="financial-card">
                    <div class="financial-header">
                        <i class="fas fa-shopping-cart"></i>
                        <span>Sales Value</span>
                    </div>
                    <div class="financial-value">TZS <?php echo number_format($salesStats['total_sales_value'] ?? 0); ?></div>
                </div>
                <div class="financial-card success">
                    <div class="financial-header">
                        <i class="fas fa-check-double"></i>
                        <span>Collected</span>
                    </div>
                    <div class="financial-value">TZS <?php echo number_format($paymentStats['total_collected'] ?? 0); ?></div>
                </div>
                <div class="financial-card warning">
                    <div class="financial-header">
                        <i class="fas fa-hourglass-half"></i>
                        <span>Balance Due</span>
                    </div>
                    <div class="financial-value">TZS <?php echo number_format($balance); ?></div>
                </div>
            </div>

            <div class="content-grid">
                <!-- Recent Plots -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-th"></i> Recent Plots</h3>
                        <a href="../plots/index.php?project=<?php echo $projectId; ?>" class="btn btn-sm btn-outline">View All</a>
                    </div>
                    <div class="table-responsive">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Plot #</th>
                                    <th>Block</th>
                                    <th>Size</th>
                                    <th>Price</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($recentPlots)): ?>
                                <tr>
                                    <td colspan="5" class="empty-row">
                                        <div class="empty-state">
                                            <i class="fas fa-th"></i>
                                            <p>No plots added yet</p>
                                            <a href="../plots/create.php?project=<?php echo $projectId; ?>" class="btn btn-primary btn-sm">Add Plots</a>
                                        </div>
                                    </td>
                                </tr>
                                <?php else: ?>
                                <?php foreach ($recentPlots as $plot): ?>
                                <tr>
                                    <td><strong><?php echo htmlspecialchars($plot['plot_number']); ?></strong></td>
                                    <td><?php echo htmlspecialchars($plot['block'] ?? '-'); ?></td>
                                    <td><?php echo number_format($plot['size']); ?> <?php echo $plot['size_unit']; ?></td>
                                    <td>TZS <?php echo number_format($plot['price']); ?></td>
                                    <td>
                                        <span class="status-badge status-<?php echo $plot['status']; ?>">
                                            <?php echo ucfirst($plot['status']); ?>
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Recent Sales -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-handshake"></i> Recent Sales</h3>
                        <a href="../sales/index.php?project=<?php echo $projectId; ?>" class="btn btn-sm btn-outline">View All</a>
                    </div>
                    <div class="table-responsive">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Plot</th>
                                    <th>Buyer</th>
                                    <th>Amount</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($recentSales)): ?>
                                <tr>
                                    <td colspan="4" class="empty-row">
                                        <div class="empty-state">
                                            <i class="fas fa-handshake"></i>
                                            <p>No sales recorded yet</p>
                                        </div>
                                    </td>
                                </tr>
                                <?php else: ?>
                                <?php foreach ($recentSales as $sale): ?>
                                <tr>
                                    <td><strong><?php echo htmlspecialchars($sale['plot_number']); ?></strong></td>
                                    <td><?php echo htmlspecialchars($sale['buyer_name']); ?></td>
                                    <td>TZS <?php echo number_format($sale['total_price']); ?></td>
                                    <td><?php echo date('M j, Y', strtotime($sale['sale_date'])); ?></td>
                                </tr>
                                <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="quick-actions">
                <a href="../plots/create.php?project=<?php echo $projectId; ?>" class="action-btn">
                    <i class="fas fa-plus"></i>
                    <span>Add Plots</span>
                </a>
                <a href="../plots/bulk-create.php?project=<?php echo $projectId; ?>" class="action-btn">
                    <i class="fas fa-layer-group"></i>
                    <span>Bulk Add</span>
                </a>
                <a href="../sales/create.php?project=<?php echo $projectId; ?>" class="action-btn">
                    <i class="fas fa-handshake"></i>
                    <span>New Sale</span>
                </a>
                <a href="../reports/projects.php" class="action-btn">
                    <i class="fas fa-chart-bar"></i>
                    <span>Reports</span>
                </a>
            </div>
        </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.875rem; 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;
        }

        .project-header-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 14px;
            padding: 1.5rem 2rem;
            color: white;
            margin-bottom: 1.5rem;
        }

        .project-meta {
            display: flex;
            gap: 1.5rem;
            flex-wrap: wrap;
            font-size: 0.9rem;
            opacity: 0.9;
        }

        .project-meta span {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .project-desc {
            margin: 1rem 0 0;
            opacity: 0.9;
            line-height: 1.6;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.25rem;
            display: flex;
            align-items: center;
            gap: 1rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
        }

        .stat-icon.blue { background: #dbeafe; color: #2563eb; }
        .stat-icon.green { background: #dcfce7; color: #16a34a; }
        .stat-icon.orange { background: #fef3c7; color: #d97706; }
        .stat-icon.red { background: #fee2e2; color: #dc2626; }

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

        .financial-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .financial-card {
            background: white;
            border-radius: 12px;
            padding: 1.25rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .financial-card.success { border-left: 4px solid #22c55e; }
        .financial-card.warning { border-left: 4px solid #f59e0b; }

        .financial-header {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.85rem;
            color: #64748b;
            margin-bottom: 0.5rem;
        }

        .financial-value { font-size: 1.1rem; font-weight: 700; color: #1e293b; }

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

        .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 {
            margin: 0;
            font-size: 0.95rem;
            font-weight: 600;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

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

        .table-responsive { overflow-x: auto; }

        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th, .data-table td {
            padding: 0.75rem 1rem;
            text-align: left;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.85rem;
        }

        .data-table th {
            background: #f8fafc;
            font-weight: 600;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #64748b;
        }

        .data-table tbody tr:hover { background: #f8fafc; }

        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .status-available { background: #dcfce7; color: #16a34a; }
        .status-reserved { background: #fef3c7; color: #d97706; }
        .status-sold { background: #fee2e2; color: #dc2626; }

        .empty-row td { padding: 2rem; }
        .empty-state { text-align: center; color: #94a3b8; }
        .empty-state i { font-size: 2rem; margin-bottom: 0.5rem; }
        .empty-state p { margin: 0.5rem 0; }

        .quick-actions {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1rem;
        }

        .action-btn {
            background: white;
            border-radius: 12px;
            padding: 1.25rem;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.5rem;
            text-decoration: none;
            color: #64748b;
            transition: all 0.2s;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            color: #667eea;
        }

        .action-btn i { font-size: 1.5rem; color: #667eea; }
        .action-btn span { font-weight: 500; font-size: 0.85rem; }

        @media (max-width: 1200px) {
            .stats-grid, .financial-grid { grid-template-columns: repeat(2, 1fr); }
        }

        @media (max-width: 992px) {
            .content-grid { grid-template-columns: 1fr; }
            .quick-actions { grid-template-columns: repeat(2, 1fr); }
        }

        @media (max-width: 576px) {
            .stats-grid, .financial-grid, .quick-actions { grid-template-columns: 1fr; }
            .header-actions { flex-wrap: wrap; }
        }
    </style>
</body>
</html>
