<?php
/**
 * Plot Grid View
 * LandSales Pro - Visual grid of plots with color-coded status
 */
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 project filter
$projectId = $_GET['project'] ?? null;

// Get user's projects
$projects = db_fetch_all("SELECT * FROM projects WHERE user_id = ? ORDER BY name", 'i', [$userId]);

// Get plots for the selected project or all
if ($projectId) {
    $selectedProject = db_fetch_one("SELECT * FROM projects WHERE id = ? AND user_id = ?", 'ii', [$projectId, $userId]);
    if (!$selectedProject) {
        header('Location: grid.php');
        exit;
    }
    $plots = db_fetch_all("SELECT p.*, b.full_name as buyer_name
        FROM plots p
        LEFT JOIN sales s ON p.id = s.plot_id AND s.status != 'cancelled'
        LEFT JOIN buyers b ON s.buyer_id = b.id
        WHERE p.project_id = ? AND p.user_id = ?
        ORDER BY p.plot_number", 'ii', [$projectId, $userId]);
} else {
    $selectedProject = null;
    $plots = [];
}

// Calculate stats
$stats = [
    'total' => 0,
    'available' => 0,
    'reserved' => 0,
    'sold' => 0
];

foreach ($plots as $plot) {
    $stats['total']++;
    $stats[$plot['status']]++;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Plot Grid - <?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">Plot Grid</h1>
            <div class="header-actions">
                <a href="index.php<?php echo $projectId ? '?project=' . $projectId : ''; ?>" class="btn btn-outline">
                    <i class="fas fa-list"></i> List View
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Project Selector -->
            <div class="project-selector">
                <div class="selector-label">Select Project:</div>
                <div class="project-tabs">
                    <?php foreach ($projects as $project): ?>
                    <a href="?project=<?php echo $project['id']; ?>"
                       class="project-tab <?php echo $projectId == $project['id'] ? 'active' : ''; ?>">
                        <?php echo htmlspecialchars($project['name']); ?>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>

            <?php if (!$selectedProject): ?>
            <!-- No Project Selected -->
            <div class="select-project-card">
                <div class="select-icon">
                    <i class="fas fa-border-all"></i>
                </div>
                <h3>Select a Project</h3>
                <p>Choose a project above to view its plot grid</p>
                <?php if (empty($projects)): ?>
                <p class="text-muted">You don't have any projects yet.</p>
                <a href="../projects/create.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Create Project
                </a>
                <?php endif; ?>
            </div>
            <?php else: ?>
            <!-- Project Info & Stats -->
            <div class="project-info">
                <div class="project-details">
                    <h2><?php echo htmlspecialchars($selectedProject['name']); ?></h2>
                    <?php if ($selectedProject['location']): ?>
                    <p><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($selectedProject['location']); ?></p>
                    <?php endif; ?>
                </div>
                <div class="project-stats">
                    <div class="stat total">
                        <div class="stat-value"><?php echo $stats['total']; ?></div>
                        <div class="stat-label">Total</div>
                    </div>
                    <div class="stat available">
                        <div class="stat-value"><?php echo $stats['available']; ?></div>
                        <div class="stat-label">Available</div>
                    </div>
                    <div class="stat reserved">
                        <div class="stat-value"><?php echo $stats['reserved']; ?></div>
                        <div class="stat-label">Reserved</div>
                    </div>
                    <div class="stat sold">
                        <div class="stat-value"><?php echo $stats['sold']; ?></div>
                        <div class="stat-label">Sold</div>
                    </div>
                </div>
            </div>

            <!-- Legend -->
            <div class="legend">
                <div class="legend-item available">
                    <span class="legend-color"></span>
                    <span>Available</span>
                </div>
                <div class="legend-item reserved">
                    <span class="legend-color"></span>
                    <span>Reserved</span>
                </div>
                <div class="legend-item sold">
                    <span class="legend-color"></span>
                    <span>Sold</span>
                </div>
            </div>

            <!-- Plot Grid -->
            <?php if (empty($plots)): ?>
            <div class="empty-grid">
                <i class="fas fa-th-large"></i>
                <h3>No Plots Yet</h3>
                <p>Add plots to this project to see them in the grid.</p>
                <a href="create.php?project=<?php echo $projectId; ?>" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add Plots
                </a>
            </div>
            <?php else: ?>
            <div class="plot-grid">
                <?php foreach ($plots as $plot): ?>
                <div class="plot-cell <?php echo $plot['status']; ?>"
                     data-plot-id="<?php echo $plot['id']; ?>"
                     onclick="showPlotDetails(<?php echo $plot['id']; ?>)">
                    <div class="plot-number"><?php echo htmlspecialchars($plot['plot_number']); ?></div>
                    <div class="plot-size"><?php echo number_format($plot['size']); ?> <?php echo $plot['size_unit']; ?></div>
                    <?php if ($plot['status'] === 'sold' && $plot['buyer_name']): ?>
                    <div class="plot-buyer"><?php echo htmlspecialchars($plot['buyer_name']); ?></div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <!-- Quick Actions -->
            <div class="quick-actions-bar">
                <a href="create.php?project=<?php echo $projectId; ?>" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add More Plots
                </a>
                <a href="bulk-create.php?project=<?php echo $projectId; ?>" class="btn btn-outline">
                    <i class="fas fa-layer-group"></i> Bulk Add
                </a>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Plot Details Modal -->
    <div class="modal-overlay" id="plotModal" onclick="closePlotModal(event)">
        <div class="modal-content">
            <button class="modal-close" onclick="closePlotModal(event)">
                <i class="fas fa-times"></i>
            </button>
            <div class="modal-body" id="plotDetails">
                <!-- Filled by JavaScript -->
            </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-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        /* Project Selector */
        .project-selector {
            background: white;
            border-radius: 12px;
            padding: 1rem 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .selector-label {
            font-size: 0.8rem;
            font-weight: 600;
            color: #64748b;
            text-transform: uppercase;
            margin-bottom: 0.75rem;
        }

        .project-tabs {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
        }

        .project-tab {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            text-decoration: none;
            color: #64748b;
            font-weight: 500;
            font-size: 0.875rem;
            background: #f1f5f9;
            transition: all 0.2s;
        }

        .project-tab:hover { background: #e2e8f0; }

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

        /* Select Project Card */
        .select-project-card {
            background: white;
            border-radius: 16px;
            padding: 4rem 2rem;
            text-align: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .select-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            margin: 0 auto 1.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            color: white;
        }

        .select-project-card h3 { margin-bottom: 0.5rem; color: #1e293b; }
        .select-project-card p { color: #64748b; }
        .text-muted { color: #94a3b8; margin-bottom: 1rem; }

        /* Project Info */
        .project-info {
            background: white;
            border-radius: 12px;
            padding: 1.25rem 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .project-details h2 {
            font-size: 1.25rem;
            color: #1e293b;
            margin: 0 0 0.25rem 0;
        }

        .project-details p {
            color: #64748b;
            font-size: 0.875rem;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .project-details p i { color: #667eea; }

        .project-stats {
            display: flex;
            gap: 1.5rem;
        }

        .project-stats .stat {
            text-align: center;
        }

        .project-stats .stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
        }

        .project-stats .stat-label {
            font-size: 0.75rem;
            color: #64748b;
        }

        .project-stats .stat.available .stat-value { color: #22c55e; }
        .project-stats .stat.reserved .stat-value { color: #f59e0b; }
        .project-stats .stat.sold .stat-value { color: #ef4444; }

        /* Legend */
        .legend {
            display: flex;
            gap: 1.5rem;
            margin-bottom: 1.5rem;
            justify-content: center;
        }

        .legend-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.85rem;
            color: #64748b;
        }

        .legend-color {
            width: 20px;
            height: 20px;
            border-radius: 4px;
        }

        .legend-item.available .legend-color { background: #22c55e; }
        .legend-item.reserved .legend-color { background: #f59e0b; }
        .legend-item.sold .legend-color { background: #ef4444; }

        /* Plot Grid */
        .plot-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
            gap: 0.75rem;
            margin-bottom: 2rem;
        }

        .plot-cell {
            aspect-ratio: 1;
            border-radius: 10px;
            padding: 0.75rem;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
            color: white;
            text-align: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .plot-cell:hover {
            transform: scale(1.05);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }

        .plot-cell.available { background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); }
        .plot-cell.reserved { background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); }
        .plot-cell.sold { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); }

        .plot-number {
            font-weight: 700;
            font-size: 1rem;
        }

        .plot-size {
            font-size: 0.65rem;
            opacity: 0.9;
            margin-top: 0.25rem;
        }

        .plot-buyer {
            font-size: 0.6rem;
            opacity: 0.85;
            margin-top: 0.25rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            max-width: 100%;
        }

        /* Empty Grid */
        .empty-grid {
            background: white;
            border-radius: 16px;
            padding: 4rem 2rem;
            text-align: center;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .empty-grid i {
            font-size: 3rem;
            color: #94a3b8;
            margin-bottom: 1rem;
        }

        .empty-grid h3 { color: #1e293b; margin-bottom: 0.5rem; }
        .empty-grid p { color: #64748b; margin-bottom: 1.5rem; }

        /* Quick Actions */
        .quick-actions-bar {
            display: flex;
            gap: 1rem;
            justify-content: center;
        }

        /* Modal */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 2000;
            align-items: center;
            justify-content: center;
            padding: 2rem;
        }

        .modal-overlay.active { display: flex; }

        .modal-content {
            background: white;
            border-radius: 16px;
            width: 100%;
            max-width: 400px;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
        }

        .modal-close {
            position: absolute;
            top: 1rem;
            right: 1rem;
            background: #f1f5f9;
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #64748b;
        }

        .modal-body { padding: 2rem; }

        @media (max-width: 768px) {
            .project-info { flex-direction: column; align-items: flex-start; }
            .project-stats { width: 100%; justify-content: space-between; }
            .plot-grid { grid-template-columns: repeat(auto-fill, minmax(80px, 1fr)); gap: 0.5rem; }
            .plot-cell { padding: 0.5rem; }
            .plot-number { font-size: 0.85rem; }
        }
    </style>

    <script>
        function showPlotDetails(plotId) {
            const modal = document.getElementById('plotModal');
            const detailsDiv = document.getElementById('plotDetails');

            // Show loading
            detailsDiv.innerHTML = '<div style="text-align: center; padding: 2rem;"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';
            modal.classList.add('active');

            // Fetch plot details via AJAX
            fetch('<?php echo SITE_URL; ?>/ajax/plot-details.php?id=' + plotId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        detailsDiv.innerHTML = data.html;
                    } else {
                        detailsDiv.innerHTML = '<p style="color: #ef4444;">Failed to load plot details</p>';
                    }
                })
                .catch(error => {
                    detailsDiv.innerHTML = '<p style="color: #ef4444;">Error loading plot details</p>';
                });
        }

        function closePlotModal(event) {
            if (event.target.classList.contains('modal-overlay') ||
                event.target.classList.contains('modal-close') ||
                event.target.closest('.modal-close')) {
                document.getElementById('plotModal').classList.remove('active');
            }
        }

        // Close on Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                document.getElementById('plotModal').classList.remove('active');
            }
        });
    </script>
</body>
</html>
