<?php
/**
 * CBC Certificates
 * List of issued Community Boundary Confirmation certificates
 */

session_start();
require_once '../db_connect.php';

$allowed_roles = ['village_chairman', 'land_officer', 'surveyor', 'district_officer', 'land_council'];
if(!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], $allowed_roles)) {
    header('Location: ../login');
    exit;
}

$user_role = $_SESSION['role'];
$village_id = $_SESSION['village_id'] ?? null;

$where = "c.status = 'active'";
if($user_role !== 'district_officer' && $village_id) {
    $where .= " AND l.village_id = $village_id";
}

$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
if($search) {
    $where .= " AND (c.certificate_number LIKE '%$search%' OR c.land_name LIKE '%$search%' OR c.owner_name LIKE '%$search%')";
}

// Check if land_certificates table exists
$table_exists = mysqli_query($conn, "SHOW TABLES LIKE 'land_certificates'");
$has_certificates = mysqli_num_rows($table_exists) > 0;

$certificates = null;
if($has_certificates) {
    $certificates = mysqli_query($conn, "
        SELECT c.*, c.land_name, c.land_size as total_area, c.land_size_unit as area_unit,
               c.owner_name, c.owner_phone,
               c.village_name
        FROM land_certificates c
        JOIN lands l ON c.land_id = l.id
        WHERE $where
        ORDER BY c.issued_at DESC
    ");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CBC Certificates - Land Secure</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .admin-main { margin-left: 280px; padding: 24px; min-height: 100vh; background: #f0f2f5; }
        @media (max-width: 1024px) { .admin-main { margin-left: 0; padding-top: 90px; } }

        .page-header { margin-bottom: 24px; }
        .page-header h1 { font-size: 24px; font-weight: 700; color: #1a1d21; display: flex; align-items: center; gap: 12px; }
        .page-header h1 i { color: #f59e0b; }

        .search-box { display: flex; gap: 12px; margin-bottom: 24px; }
        .search-input { flex: 1; max-width: 400px; padding: 12px 16px; border: 2px solid #e2e8f0; border-radius: 10px; }
        .search-btn { padding: 12px 24px; background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; border: none; border-radius: 10px; font-weight: 600; cursor: pointer; }

        .certs-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 20px; }

        .cert-card { background: white; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.05); border-top: 4px solid #f59e0b; }
        .cert-header { padding: 20px; background: linear-gradient(135deg, rgba(245, 158, 11, 0.1) 0%, rgba(234, 88, 12, 0.1) 100%); }
        .cert-number { font-size: 12px; color: #92400e; font-weight: 600; margin-bottom: 4px; }
        .cert-land { font-size: 18px; font-weight: 600; color: #1a1d21; margin: 0; }

        .cert-body { padding: 20px; }
        .cert-owner { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px solid #f0f2f5; }
        .cert-avatar { width: 44px; height: 44px; border-radius: 12px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); display: flex; align-items: center; justify-content: center; color: white; font-weight: 700; }
        .owner-name { font-weight: 600; color: #1a1d21; }
        .owner-phone { font-size: 13px; color: #64748b; }

        .cert-details { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
        .detail { text-align: center; padding: 12px; background: #f8fafc; border-radius: 8px; }
        .detail .value { font-size: 16px; font-weight: 600; color: #1a1d21; }
        .detail .label { font-size: 11px; color: #64748b; text-transform: uppercase; }

        .cert-actions { padding: 16px 20px; background: #f8fafc; display: flex; gap: 10px; }
        .btn { flex: 1; padding: 10px; border-radius: 8px; font-size: 13px; font-weight: 600; text-align: center; text-decoration: none; border: none; cursor: pointer; }
        .btn-primary { background: linear-gradient(135deg, #f59e0b 0%, #ea580c 100%); color: white; }
        .btn-outline { background: white; border: 2px solid #e2e8f0; color: #64748b; }

        .empty-state { text-align: center; padding: 60px; background: white; border-radius: 16px; color: #64748b; }
        .empty-state i { font-size: 48px; color: #f59e0b; margin-bottom: 16px; }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <div class="page-header">
            <h1><i class="fas fa-certificate"></i> CBC Certificates</h1>
            <p style="color: #64748b; margin: 8px 0 0;">Vyeti vya Uthibitisho wa Mipaka / Issued boundary confirmation certificates</p>
        </div>

        <form method="GET" class="search-box">
            <input type="text" name="search" class="search-input" placeholder="Search by certificate number, land or owner..." value="<?php echo htmlspecialchars($search); ?>">
            <button type="submit" class="search-btn"><i class="fas fa-search"></i> Search</button>
        </form>

        <?php if(!$has_certificates): ?>
        <div class="empty-state">
            <i class="fas fa-database"></i>
            <h3>Certificates System Not Set Up</h3>
            <p>The land_certificates table needs to be created.</p>
            <p style="margin-top: 10px; font-size: 13px;">Run <code>database_cbc_system.sql</code> in phpMyAdmin to set up the CBC system tables.</p>
        </div>
        <?php elseif($certificates && mysqli_num_rows($certificates) > 0): ?>
        <div class="certs-grid">
            <?php while($cert = mysqli_fetch_assoc($certificates)): ?>
            <div class="cert-card">
                <div class="cert-header">
                    <div class="cert-number">#<?php echo htmlspecialchars($cert['certificate_number']); ?></div>
                    <h3 class="cert-land"><?php echo htmlspecialchars($cert['land_name']); ?></h3>
                </div>
                <div class="cert-body">
                    <div class="cert-owner">
                        <div class="cert-avatar"><?php echo strtoupper(substr($cert['owner_name'], 0, 1)); ?></div>
                        <div>
                            <div class="owner-name"><?php echo htmlspecialchars($cert['owner_name']); ?></div>
                            <div class="owner-phone"><?php echo htmlspecialchars($cert['owner_phone']); ?></div>
                        </div>
                    </div>
                    <div class="cert-details">
                        <div class="detail">
                            <div class="value"><?php echo $cert['total_area']; ?> <?php echo $cert['area_unit']; ?></div>
                            <div class="label">Area</div>
                        </div>
                        <div class="detail">
                            <div class="value"><?php echo date('M j, Y', strtotime($cert['issued_at'])); ?></div>
                            <div class="label">Issued</div>
                        </div>
                    </div>
                </div>
                <div class="cert-actions">
                    <a href="../cbc-certificate/<?php echo $cert['id']; ?>" class="btn btn-primary" target="_blank"><i class="fas fa-eye"></i> View</a>
                    <a href="../cbc-certificate/<?php echo $cert['id']; ?>?print=1" class="btn btn-outline" target="_blank"><i class="fas fa-print"></i> Print</a>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        <?php else: ?>
        <div class="empty-state">
            <i class="fas fa-certificate"></i>
            <h3>No Certificates Issued</h3>
            <p>Hakuna vyeti vilivyotolewa bado / Certificates will appear here once lands are fully verified</p>
        </div>
        <?php endif; ?>
    </main>
</body>
</html>
