<?php
/**
 * Plots List
 * LandSales Pro - Manage plots
 */
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'];

// Filters
$projectId = $_GET['project'] ?? null;
$statusFilter = $_GET['status'] ?? 'all';

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

// Build query
$whereClause = "WHERE p.user_id = ?";
$params = [$userId];
$types = 'i';

if ($projectId) {
    $whereClause .= " AND p.project_id = ?";
    $params[] = intval($projectId);
    $types .= 'i';
}

if ($statusFilter !== 'all') {
    $whereClause .= " AND p.status = ?";
    $params[] = $statusFilter;
    $types .= 's';
}

// Pagination
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$total = db_fetch_one("SELECT COUNT(*) as count FROM plots p {$whereClause}", $types, $params)['count'];
$totalPages = ceil($total / $perPage);

$plots = db_fetch_all("SELECT p.*, pr.name as project_name,
    p.price_per_sqm, p.center_latitude, p.center_longitude,
    (SELECT COUNT(*) FROM plot_beacons WHERE plot_id = p.id) as beacon_count
    FROM plots p
    JOIN projects pr ON p.project_id = pr.id
    {$whereClause}
    ORDER BY pr.name, p.plot_number
    LIMIT {$perPage} OFFSET {$offset}", $types, $params);

// Stats
$stats = 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
    FROM plots WHERE user_id = ?", 'i', [$userId]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Plots - <?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">Plots</h1>
            <div class="header-actions">
                <a href="grid.php<?php echo $projectId ? '?project=' . $projectId : ''; ?>" class="btn btn-outline">
                    <i class="fas fa-border-all"></i> Grid View
                </a>
                <a href="create.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add Plots
                </a>
            </div>
        </div>

        <div class="content-wrapper">
            <!-- Stats -->
            <div class="stats-row">
                <div class="stat-mini">
                    <i class="fas fa-th"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($stats['total']); ?></div>
                        <div class="stat-label">Total</div>
                    </div>
                </div>
                <div class="stat-mini available">
                    <i class="fas fa-check-circle"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($stats['available']); ?></div>
                        <div class="stat-label">Available</div>
                    </div>
                </div>
                <div class="stat-mini reserved">
                    <i class="fas fa-clock"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($stats['reserved']); ?></div>
                        <div class="stat-label">Reserved</div>
                    </div>
                </div>
                <div class="stat-mini sold">
                    <i class="fas fa-handshake"></i>
                    <div>
                        <div class="stat-value"><?php echo number_format($stats['sold']); ?></div>
                        <div class="stat-label">Sold</div>
                    </div>
                </div>
            </div>

            <!-- Filters -->
            <div class="filters-card">
                <form class="filters-form" method="GET">
                    <div class="filter-group">
                        <label>Project</label>
                        <select name="project" class="form-control" onchange="this.form.submit()">
                            <option value="">All Projects</option>
                            <?php foreach ($projects as $project): ?>
                            <option value="<?php echo $project['id']; ?>" <?php echo $projectId == $project['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($project['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>Status</label>
                        <select name="status" class="form-control" onchange="this.form.submit()">
                            <option value="all">All Status</option>
                            <option value="available" <?php echo $statusFilter === 'available' ? 'selected' : ''; ?>>Available</option>
                            <option value="reserved" <?php echo $statusFilter === 'reserved' ? 'selected' : ''; ?>>Reserved</option>
                            <option value="sold" <?php echo $statusFilter === 'sold' ? 'selected' : ''; ?>>Sold</option>
                        </select>
                    </div>
                </form>
            </div>

            <!-- Table -->
            <div class="card">
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Plot No.</th>
                                <th>Project</th>
                                <th>Size</th>
                                <th>Price</th>
                                <th>Per sqm</th>
                                <th>GPS</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($plots)): ?>
                            <tr>
                                <td colspan="8" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-th"></i>
                                        <p>No plots found</p>
                                        <a href="create.php" class="btn btn-primary btn-sm">Add Plots</a>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($plots as $plot): ?>
                            <tr>
                                <td>
                                    <span class="plot-number"><?php echo htmlspecialchars($plot['plot_number']); ?></span>
                                </td>
                                <td><?php echo htmlspecialchars($plot['project_name']); ?></td>
                                <td><?php echo number_format($plot['size']); ?> <?php echo $plot['size_unit']; ?></td>
                                <td>TZS <?php echo number_format($plot['price']); ?></td>
                                <td>
                                    <?php if ($plot['price_per_sqm']): ?>
                                    TZS <?php echo number_format($plot['price_per_sqm']); ?>
                                    <?php else: ?>
                                    <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($plot['beacon_count'] > 0): ?>
                                    <span class="gps-badge has-gps" title="<?php echo $plot['beacon_count']; ?> beacons">
                                        <i class="fas fa-map-pin"></i>
                                        <span class="beacon-num"><?php echo $plot['beacon_count']; ?></span>
                                    </span>
                                    <?php else: ?>
                                    <span class="gps-badge no-gps" title="No GPS coordinates">
                                        <i class="fas fa-map-marker-alt"></i>
                                    </span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="status-badge status-<?php echo $plot['status']; ?>">
                                        <?php echo ucfirst($plot['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="view.php?id=<?php echo $plot['id']; ?>" class="btn-icon" title="View">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <?php if ($plot['status'] === 'available'): ?>
                                        <a href="../sales/create.php?plot_id=<?php echo $plot['id']; ?>" class="btn-icon success" title="Record Sale">
                                            <i class="fas fa-handshake"></i>
                                        </a>
                                        <?php endif; ?>
                                        <a href="edit.php?id=<?php echo $plot['id']; ?>" class="btn-icon" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                <div class="pagination-wrapper">
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>&project=<?php echo $projectId; ?>&status=<?php echo $statusFilter; ?>" class="page-link">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                        <?php endif; ?>

                        <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                        <a href="?page=<?php echo $i; ?>&project=<?php echo $projectId; ?>&status=<?php echo $statusFilter; ?>"
                           class="page-link <?php echo $i === $page ? 'active' : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                        <?php endfor; ?>

                        <?php if ($page < $totalPages): ?>
                        <a href="?page=<?php echo $page + 1; ?>&project=<?php echo $projectId; ?>&status=<?php echo $statusFilter; ?>" class="page-link">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </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; }

        .stats-row {
            display: flex;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }

        .stat-mini {
            flex: 1;
            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.available { border-left: 3px solid #22c55e; }
        .stat-mini.available i { background: #dcfce7; color: #16a34a; }
        .stat-mini.reserved { border-left: 3px solid #f59e0b; }
        .stat-mini.reserved i { background: #fef3c7; color: #d97706; }
        .stat-mini.sold { border-left: 3px solid #ef4444; }
        .stat-mini.sold i { background: #fee2e2; color: #dc2626; }

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

        .filters-card {
            background: white;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .filters-form { display: flex; gap: 1rem; }
        .filter-group { display: flex; align-items: center; gap: 0.5rem; }
        .filter-group label { font-size: 0.85rem; font-weight: 500; color: #64748b; }
        .form-control { padding: 0.5rem 0.75rem; border: 1px solid #e2e8f0; border-radius: 6px; font-size: 0.85rem; }

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

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

        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 1rem; text-align: left; border-bottom: 1px solid #f1f5f9; }
        .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; }

        .plot-number { font-weight: 600; color: #667eea; }

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

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

        .text-muted { color: #94a3b8; }

        .gps-badge {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 0.75rem;
        }

        .gps-badge.has-gps { background: #dcfce7; color: #16a34a; }
        .gps-badge.no-gps { background: #f1f5f9; color: #cbd5e1; }
        .gps-badge .beacon-num { font-size: 0.65rem; font-weight: 600; margin-left: 2px; }

        .action-buttons { display: flex; gap: 0.5rem; }

        .btn-icon {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #64748b;
            background: #f1f5f9;
            text-decoration: none;
            transition: all 0.2s;
        }

        .btn-icon:hover { background: #667eea; color: white; }
        .btn-icon.success:hover { background: #22c55e; }

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

        .pagination-wrapper { padding: 1rem; border-top: 1px solid #f1f5f9; display: flex; justify-content: center; }
        .pagination { display: flex; gap: 0.25rem; }
        .page-link { padding: 0.5rem 0.75rem; border-radius: 6px; text-decoration: none; color: #64748b; font-weight: 500; }
        .page-link:hover { background: #f1f5f9; }
        .page-link.active { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }

        @media (max-width: 768px) {
            .stats-row { flex-wrap: wrap; }
            .stat-mini { min-width: calc(50% - 0.5rem); }
            .filters-form { flex-direction: column; }
        }
    </style>
</body>
</html>
