<?php
/**
 * Request Land Verification
 * Allows users to request village verification for their land
 */

define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';

initSecureSession();

if(!isAuthenticated() || !validateSession()) {
    header('Location: login');
    exit;
}

$user_id = $_SESSION['user_id'];
$message = '';
$error = '';

// Get user's lands that are eligible for verification request
$lands = mysqli_query($conn, "
    SELECT l.*,
           r.name as region_name,
           d.name as district_name,
           v.name as village_name,
           v.id as village_id,
           (SELECT COUNT(*) FROM beacon_points WHERE land_id = l.id) as beacon_count
    FROM lands l
    LEFT JOIN regions r ON l.region_id = r.id
    LEFT JOIN districts d ON l.district_id = d.id
    LEFT JOIN villages v ON l.village_id = v.id
    WHERE l.user_id = $user_id
    ORDER BY l.created_at DESC
");

// Check for existing verification requests
$existing_requests = [];
$req_result = mysqli_query($conn, "SELECT land_id, status FROM verification_requests WHERE user_id = $user_id");
if($req_result) {
    while($req = mysqli_fetch_assoc($req_result)) {
        $existing_requests[$req['land_id']] = $req['status'];
    }
}

// Get regions for dropdown
$regions = mysqli_query($conn, "SELECT id, name FROM regions ORDER BY name");

// Handle form submission
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $land_id = intval($_POST['land_id'] ?? 0);
    $village_id = intval($_POST['village_id'] ?? 0);
    $notes = mysqli_real_escape_string($conn, trim($_POST['notes'] ?? ''));

    // Verify this land belongs to the user
    $land_check = mysqli_query($conn, "SELECT id, land_name, status FROM lands WHERE id = $land_id AND user_id = $user_id");
    $land = mysqli_fetch_assoc($land_check);

    if(!$land) {
        $error = 'Land not found or you do not have permission to request verification for this land.';
    } elseif(!$village_id) {
        $error = 'Please select the village where this land is located.';
    } else {
        // Check if request already exists
        $existing = mysqli_query($conn, "SELECT id FROM verification_requests WHERE land_id = $land_id AND status IN ('pending', 'in_progress')");
        if(mysqli_num_rows($existing) > 0) {
            $error = 'A verification request for this land is already pending.';
        } else {
            // Update land with village_id if not set
            if($village_id > 0) {
                // Get region and district from village
                $village_info = mysqli_fetch_assoc(mysqli_query($conn, "
                    SELECT v.id, v.district_id, d.region_id
                    FROM villages v
                    JOIN districts d ON v.district_id = d.id
                    WHERE v.id = $village_id
                "));

                if($village_info) {
                    mysqli_query($conn, "UPDATE lands SET
                        village_id = {$village_info['id']},
                        district_id = {$village_info['district_id']},
                        region_id = {$village_info['region_id']},
                        status = 'pending_neighbor'
                        WHERE id = $land_id");
                }
            }

            // Create verification request
            $request_number = 'VRQ-' . date('Y') . '-' . str_pad(rand(1, 99999), 5, '0', STR_PAD_LEFT);

            $sql = "INSERT INTO verification_requests (
                request_number, land_id, user_id, village_id,
                request_type, notes, status, created_at
            ) VALUES (
                '$request_number', $land_id, $user_id, $village_id,
                'village_verification', '$notes', 'pending', NOW()
            )";

            if(mysqli_query($conn, $sql)) {
                // Update land status
                mysqli_query($conn, "UPDATE lands SET status = 'pending_neighbor' WHERE id = $land_id AND status IN ('draft', 'active')");

                // Log the activity
                mysqli_query($conn, "INSERT INTO activity_logs (user_id, action, description, ip_address)
                    VALUES ($user_id, 'verification_request', 'Requested verification for land #$land_id', '{$_SERVER['REMOTE_ADDR']}')");

                // Create notification for village officials
                $village_officials = mysqli_query($conn, "
                    SELECT id FROM users
                    WHERE village_id = $village_id
                    AND role IN ('village_chairman', 'land_officer', 'land_council')
                    AND status = 'approved'
                ");

                while($official = mysqli_fetch_assoc($village_officials)) {
                    mysqli_query($conn, "INSERT INTO cbc_notifications (
                        user_id, notification_type, title, message, land_id, created_at
                    ) VALUES (
                        {$official['id']}, 'village_review_pending',
                        'New Verification Request',
                        'A landowner has requested verification for {$land['land_name']}',
                        $land_id, NOW()
                    )");
                }

                $message = "Verification request submitted successfully! Request #$request_number. Village officials will review your land.";

                // Refresh lands list
                $lands = mysqli_query($conn, "
                    SELECT l.*, r.name as region_name, d.name as district_name, v.name as village_name, v.id as village_id,
                           (SELECT COUNT(*) FROM beacon_points WHERE land_id = l.id) as beacon_count
                    FROM lands l
                    LEFT JOIN regions r ON l.region_id = r.id
                    LEFT JOIN districts d ON l.district_id = d.id
                    LEFT JOIN villages v ON l.village_id = v.id
                    WHERE l.user_id = $user_id
                    ORDER BY l.created_at DESC
                ");

                // Refresh existing requests
                $existing_requests = [];
                $req_result = mysqli_query($conn, "SELECT land_id, status FROM verification_requests WHERE user_id = $user_id");
                if($req_result) {
                    while($req = mysqli_fetch_assoc($req_result)) {
                        $existing_requests[$req['land_id']] = $req['status'];
                    }
                }
            } else {
                $error = 'Failed to submit request. Please try again.';
            }
        }
    }
}

// Get verification request history
$request_history = mysqli_query($conn, "
    SELECT vr.*, l.land_name, v.name as village_name
    FROM verification_requests vr
    JOIN lands l ON vr.land_id = l.id
    LEFT JOIN villages v ON vr.village_id = v.id
    WHERE vr.user_id = $user_id
    ORDER BY vr.created_at DESC
    LIMIT 10
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Request Verification - 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">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="app-main">
        <!-- Page Header -->
        <div class="page-header">
            <div class="page-header-content">
                <div class="page-title">
                    <h1><i class="fas fa-clipboard-check"></i> Request Verification</h1>
                    <p>Submit your land for village verification / Omba Uhakiki wa Ardhi</p>
                </div>
            </div>
        </div>

        <?php if($message): ?>
        <div class="alert alert-success">
            <i class="fas fa-check-circle"></i> <?php echo $message; ?>
        </div>
        <?php endif; ?>

        <?php if($error): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
        </div>
        <?php endif; ?>

        <!-- Info Card -->
        <div class="info-card">
            <div class="info-icon">
                <i class="fas fa-info-circle"></i>
            </div>
            <div class="info-content">
                <h4>How Verification Works / Jinsi Uhakiki Unavyofanya Kazi</h4>
                <ol>
                    <li><strong>Select Land</strong> - Choose the land you want to verify / Chagua ardhi unayotaka kuhakiki</li>
                    <li><strong>Select Village</strong> - Choose the village where your land is located / Chagua kijiji ambapo ardhi yako iko</li>
                    <li><strong>Neighbor Confirmation</strong> - Your neighbors will be asked to confirm boundaries / Majirani wako wataulizwa kuthibitisha mipaka</li>
                    <li><strong>Village Review</strong> - Village chairman/land officer will verify / Mwenyekiti/Afisa ardhi watahakiki</li>
                    <li><strong>Professional Survey</strong> - A surveyor will do final verification / Mpima ardhi atafanya uhakiki wa mwisho</li>
                    <li><strong>Certificate</strong> - Get your digital CBC certificate / Pata cheti chako cha CBC</li>
                </ol>
            </div>
        </div>

        <div class="content-grid">
            <!-- Your Lands -->
            <div class="content-card">
                <div class="card-header-custom">
                    <h3><i class="fas fa-map"></i> Your Lands / Ardhi Zako</h3>
                </div>
                <div class="card-body">
                    <?php if(mysqli_num_rows($lands) > 0): ?>
                    <div class="lands-list">
                        <?php while($land = mysqli_fetch_assoc($lands)): ?>
                        <?php
                            $has_pending_request = isset($existing_requests[$land['id']]) && $existing_requests[$land['id']] == 'pending';
                            $is_verifiable = in_array($land['status'], ['draft', 'active', 'pending_neighbor']) && $land['beacon_count'] >= 3;
                            $status_class = '';
                            switch($land['status']) {
                                case 'draft':
                                case 'active': $status_class = 'status-draft'; break;
                                case 'pending_neighbor':
                                case 'neighbor_verified':
                                case 'pending_village': $status_class = 'status-pending'; break;
                                case 'village_verified':
                                case 'pending_survey':
                                case 'surveyor_verified':
                                case 'fully_verified': $status_class = 'status-verified'; break;
                                case 'disputed': $status_class = 'status-disputed'; break;
                            }
                        ?>
                        <div class="land-item <?php echo $has_pending_request ? 'has-request' : ''; ?>">
                            <div class="land-icon">
                                <i class="fas fa-map-marked-alt"></i>
                            </div>
                            <div class="land-info">
                                <h4><?php echo htmlspecialchars($land['land_name']); ?></h4>
                                <p class="land-location">
                                    <i class="fas fa-map-marker-alt"></i>
                                    <?php
                                    $location_parts = [];
                                    if($land['village_name']) $location_parts[] = $land['village_name'];
                                    if($land['district_name']) $location_parts[] = $land['district_name'];
                                    if($land['region_name']) $location_parts[] = $land['region_name'];
                                    echo !empty($location_parts) ? implode(', ', $location_parts) : 'Location not set';
                                    ?>
                                </p>
                                <div class="land-meta">
                                    <span><i class="fas fa-ruler-combined"></i> <?php echo number_format($land['total_area'], 2); ?> <?php echo $land['area_unit']; ?></span>
                                    <span><i class="fas fa-map-pin"></i> <?php echo $land['beacon_count']; ?> points</span>
                                </div>
                            </div>
                            <div class="land-status">
                                <span class="status-badge <?php echo $status_class; ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $land['status'])); ?>
                                </span>
                                <?php if($has_pending_request): ?>
                                <span class="request-badge">
                                    <i class="fas fa-hourglass-half"></i> Request Pending
                                </span>
                                <?php endif; ?>
                            </div>
                            <div class="land-actions">
                                <?php if($is_verifiable && !$has_pending_request): ?>
                                <button type="button" class="btn-request" onclick="openRequestModal(<?php echo $land['id']; ?>, '<?php echo addslashes($land['land_name']); ?>', <?php echo $land['village_id'] ?: 0; ?>)">
                                    <i class="fas fa-paper-plane"></i> Request Verification
                                </button>
                                <?php elseif($land['beacon_count'] < 3): ?>
                                <a href="view_land?id=<?php echo $land['id']; ?>" class="btn-outline-small">
                                    <i class="fas fa-plus"></i> Add More Points
                                </a>
                                <?php elseif(in_array($land['status'], ['fully_verified'])): ?>
                                <a href="cbc-certificate/<?php echo $land['id']; ?>" class="btn-success-small">
                                    <i class="fas fa-certificate"></i> View Certificate
                                </a>
                                <?php else: ?>
                                <span class="text-muted"><i class="fas fa-clock"></i> In Progress</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    </div>
                    <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-map"></i>
                        <h4>No Lands Registered</h4>
                        <p>Register your land first before requesting verification</p>
                        <a href="add_land" class="btn-primary">
                            <i class="fas fa-plus"></i> Register New Land
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Request History -->
            <div class="content-card">
                <div class="card-header-custom">
                    <h3><i class="fas fa-history"></i> Request History</h3>
                </div>
                <div class="card-body">
                    <?php if($request_history && mysqli_num_rows($request_history) > 0): ?>
                    <div class="history-list">
                        <?php while($req = mysqli_fetch_assoc($request_history)): ?>
                        <?php
                            $req_status_class = '';
                            switch($req['status']) {
                                case 'pending': $req_status_class = 'status-pending'; break;
                                case 'in_progress': $req_status_class = 'status-progress'; break;
                                case 'completed': $req_status_class = 'status-completed'; break;
                                case 'rejected': $req_status_class = 'status-rejected'; break;
                            }
                        ?>
                        <div class="history-item">
                            <div class="history-icon">
                                <i class="fas fa-file-alt"></i>
                            </div>
                            <div class="history-info">
                                <h5><?php echo htmlspecialchars($req['land_name']); ?></h5>
                                <p>
                                    <span class="request-number">#<?php echo $req['request_number']; ?></span>
                                    <?php if($req['village_name']): ?>
                                    <span><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($req['village_name']); ?></span>
                                    <?php endif; ?>
                                </p>
                                <span class="history-date">
                                    <i class="fas fa-calendar"></i> <?php echo date('M d, Y H:i', strtotime($req['created_at'])); ?>
                                </span>
                            </div>
                            <span class="status-badge <?php echo $req_status_class; ?>">
                                <?php echo ucfirst($req['status']); ?>
                            </span>
                        </div>
                        <?php endwhile; ?>
                    </div>
                    <?php else: ?>
                    <div class="empty-state-small">
                        <i class="fas fa-inbox"></i>
                        <p>No verification requests yet</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </main>

    <!-- Request Modal -->
    <div class="modal fade" id="requestModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title"><i class="fas fa-paper-plane"></i> Request Verification</h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="land_id" id="modalLandId">

                        <div class="selected-land">
                            <label>Land / Ardhi:</label>
                            <strong id="modalLandName"></strong>
                        </div>

                        <div class="form-group">
                            <label>Region / Mkoa <span class="required">*</span></label>
                            <select id="modalRegionSelect" class="form-control" required>
                                <option value="">Select Region / Chagua Mkoa</option>
                                <?php
                                mysqli_data_seek($regions, 0);
                                while($region = mysqli_fetch_assoc($regions)):
                                ?>
                                <option value="<?php echo $region['id']; ?>"><?php echo htmlspecialchars($region['name']); ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>District / Wilaya <span class="required">*</span></label>
                            <select id="modalDistrictSelect" class="form-control" disabled required>
                                <option value="">Select District / Chagua Wilaya</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Village / Kijiji <span class="required">*</span></label>
                            <select name="village_id" id="modalVillageId" class="form-control" disabled required>
                                <option value="">Select Village / Chagua Kijiji</option>
                            </select>
                            <small class="text-muted">Select the village where this land is located / Chagua kijiji ambapo ardhi yako iko</small>
                        </div>

                        <div class="form-group">
                            <label>Additional Notes / Maelezo Zaidi (Optional)</label>
                            <textarea name="notes" class="form-control" rows="3"
                                placeholder="Any additional information about your land or verification request..."></textarea>
                        </div>

                        <div class="verification-info">
                            <h6><i class="fas fa-info-circle"></i> What happens next?</h6>
                            <ul>
                                <li>Village officials will be notified of your request</li>
                                <li>They will schedule a visit or meeting to verify your land</li>
                                <li>Your neighbors will be asked to confirm boundaries</li>
                                <li>You will receive notifications at each step</li>
                            </ul>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane"></i> Submit Request
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <style>
    .page-header {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        border-radius: 20px;
        padding: 30px;
        margin-bottom: 30px;
        color: white;
    }

    .page-title h1 {
        font-size: 28px;
        font-weight: 700;
        margin: 0 0 8px 0;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .page-title p {
        margin: 0;
        opacity: 0.9;
    }

    .info-card {
        background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
        border-radius: 16px;
        padding: 24px;
        margin-bottom: 30px;
        display: flex;
        gap: 20px;
        border-left: 4px solid #667eea;
    }

    .info-icon {
        width: 50px;
        height: 50px;
        border-radius: 12px;
        background: #667eea;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 24px;
        flex-shrink: 0;
    }

    .info-content h4 {
        font-size: 16px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 12px;
    }

    .info-content ol {
        margin: 0;
        padding-left: 20px;
        color: #475569;
        font-size: 14px;
    }

    .info-content li {
        margin-bottom: 6px;
    }

    .content-grid {
        display: grid;
        grid-template-columns: 2fr 1fr;
        gap: 24px;
    }

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

    .content-card {
        background: white;
        border-radius: 20px;
        box-shadow: 0 4px 20px rgba(0,0,0,0.05);
        overflow: hidden;
    }

    .card-header-custom {
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;
    }

    .card-header-custom h3 {
        font-size: 16px;
        font-weight: 600;
        margin: 0;
        color: #1e293b;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .card-body {
        padding: 20px 24px;
    }

    .lands-list {
        display: flex;
        flex-direction: column;
        gap: 16px;
    }

    .land-item {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 16px;
        background: #f8fafc;
        border-radius: 12px;
        transition: all 0.3s;
    }

    .land-item:hover {
        background: #f1f5f9;
    }

    .land-item.has-request {
        background: linear-gradient(135deg, rgba(251, 191, 36, 0.1) 0%, rgba(245, 158, 11, 0.1) 100%);
        border: 1px solid rgba(251, 191, 36, 0.3);
    }

    .land-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 20px;
        flex-shrink: 0;
    }

    .land-info {
        flex: 1;
        min-width: 0;
    }

    .land-info h4 {
        font-size: 15px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 4px;
    }

    .land-location {
        font-size: 13px;
        color: #64748b;
        margin: 0 0 8px;
    }

    .land-meta {
        display: flex;
        gap: 16px;
        font-size: 12px;
        color: #94a3b8;
    }

    .land-status {
        display: flex;
        flex-direction: column;
        gap: 6px;
        align-items: flex-end;
    }

    .status-badge {
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 600;
    }

    .status-draft { background: #e2e8f0; color: #475569; }
    .status-pending { background: #fef3c7; color: #d97706; }
    .status-verified { background: #d1fae5; color: #059669; }
    .status-disputed { background: #fee2e2; color: #dc2626; }
    .status-progress { background: #dbeafe; color: #2563eb; }
    .status-completed { background: #d1fae5; color: #059669; }
    .status-rejected { background: #fee2e2; color: #dc2626; }

    .request-badge {
        font-size: 11px;
        color: #f59e0b;
        display: flex;
        align-items: center;
        gap: 4px;
    }

    .land-actions {
        flex-shrink: 0;
    }

    .btn-request {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 10px 18px;
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        color: white;
        border: none;
        border-radius: 10px;
        font-weight: 600;
        font-size: 13px;
        cursor: pointer;
        transition: all 0.3s;
    }

    .btn-request:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(17, 153, 142, 0.3);
    }

    .btn-outline-small {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 8px 14px;
        background: white;
        color: #64748b;
        border: 2px solid #e2e8f0;
        border-radius: 8px;
        font-size: 12px;
        text-decoration: none;
        transition: all 0.3s;
    }

    .btn-outline-small:hover {
        border-color: #11998e;
        color: #11998e;
        text-decoration: none;
    }

    .btn-success-small {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 8px 14px;
        background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
        color: white;
        border-radius: 8px;
        font-size: 12px;
        text-decoration: none;
        transition: all 0.3s;
    }

    .btn-success-small:hover {
        transform: translateY(-2px);
        color: white;
        text-decoration: none;
    }

    .empty-state {
        text-align: center;
        padding: 40px;
        color: #64748b;
    }

    .empty-state i {
        font-size: 48px;
        margin-bottom: 16px;
        opacity: 0.5;
    }

    .empty-state h4 {
        margin: 0 0 8px;
        color: #1e293b;
    }

    .empty-state-small {
        text-align: center;
        padding: 30px;
        color: #94a3b8;
    }

    .empty-state-small i {
        font-size: 32px;
        margin-bottom: 12px;
    }

    .btn-primary {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 12px 24px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 12px;
        font-weight: 600;
        text-decoration: none;
        transition: all 0.3s;
    }

    .history-list {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .history-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        background: #f8fafc;
        border-radius: 10px;
    }

    .history-icon {
        width: 36px;
        height: 36px;
        border-radius: 8px;
        background: #e2e8f0;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #64748b;
    }

    .history-info {
        flex: 1;
    }

    .history-info h5 {
        font-size: 14px;
        font-weight: 600;
        color: #1e293b;
        margin: 0 0 4px;
    }

    .history-info p {
        font-size: 12px;
        color: #64748b;
        margin: 0;
        display: flex;
        gap: 12px;
    }

    .request-number {
        font-family: monospace;
        background: #e2e8f0;
        padding: 2px 6px;
        border-radius: 4px;
    }

    .history-date {
        font-size: 11px;
        color: #94a3b8;
    }

    .alert {
        border: none;
        border-radius: 14px;
        padding: 16px 20px;
        margin-bottom: 25px;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .alert-success {
        background: linear-gradient(135deg, rgba(34, 197, 94, 0.1) 0%, rgba(22, 163, 74, 0.1) 100%);
        color: #166534;
        border-left: 4px solid #22c55e;
    }

    .alert-danger {
        background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(220, 38, 38, 0.1) 100%);
        color: #991b1b;
        border-left: 4px solid #ef4444;
    }

    /* Modal Styles */
    .modal-content {
        border: none;
        border-radius: 20px;
    }

    .modal-header {
        border-bottom: 1px solid #f1f5f9;
        padding: 20px 24px;
    }

    .modal-body {
        padding: 24px;
    }

    .modal-footer {
        border-top: 1px solid #f1f5f9;
        padding: 16px 24px;
    }

    .selected-land {
        background: #f8fafc;
        padding: 14px 18px;
        border-radius: 10px;
        margin-bottom: 20px;
    }

    .selected-land label {
        font-size: 12px;
        color: #64748b;
        margin-bottom: 4px;
    }

    .selected-land strong {
        font-size: 16px;
        color: #1e293b;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-group label {
        display: block;
        font-weight: 500;
        color: #475569;
        margin-bottom: 8px;
    }

    .required {
        color: #ef4444;
    }

    .form-control {
        border-radius: 10px;
        border: 2px solid #e2e8f0;
        padding: 12px 16px;
        transition: all 0.3s;
    }

    .form-control:focus {
        border-color: #11998e;
        box-shadow: 0 0 0 4px rgba(17, 153, 142, 0.1);
    }

    .verification-info {
        background: linear-gradient(135deg, rgba(17, 153, 142, 0.1) 0%, rgba(56, 239, 125, 0.1) 100%);
        border-radius: 12px;
        padding: 16px;
        margin-top: 20px;
    }

    .verification-info h6 {
        font-size: 14px;
        font-weight: 600;
        color: #11998e;
        margin: 0 0 12px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .verification-info ul {
        margin: 0;
        padding-left: 20px;
        color: #475569;
        font-size: 13px;
    }

    .verification-info li {
        margin-bottom: 4px;
    }

    .btn {
        border-radius: 10px;
        padding: 12px 24px;
        font-weight: 600;
        transition: all 0.3s;
    }

    .btn-secondary {
        background: #f1f5f9;
        border: none;
        color: #64748b;
    }

    @media (max-width: 768px) {
        .page-header {
            padding: 20px;
        }

        .page-title h1 {
            font-size: 22px;
        }

        .info-card {
            flex-direction: column;
        }

        .land-item {
            flex-direction: column;
            text-align: center;
        }

        .land-status {
            align-items: center;
        }
    }
    </style>

    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        function openRequestModal(landId, landName, villageId) {
            $('#modalLandId').val(landId);
            $('#modalLandName').text(landName);

            // Reset dropdowns
            $('#modalRegionSelect').val('');
            $('#modalDistrictSelect').prop('disabled', true).html('<option value="">Select District / Chagua Wilaya</option>');
            $('#modalVillageId').prop('disabled', true).html('<option value="">Select Village / Chagua Kijiji</option>');

            // If village is already set, pre-select it
            if (villageId > 0) {
                // Fetch village details to pre-populate all dropdowns
                fetch('api/get_locations.php?action=village_details&village_id=' + villageId)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            const v = data.data;
                            // Set region
                            $('#modalRegionSelect').val(v.region_id);

                            // Load and set district
                            fetch('api/get_locations.php?action=districts&region_id=' + v.region_id)
                                .then(response => response.json())
                                .then(districtData => {
                                    if (districtData.success) {
                                        let options = '<option value="">Select District / Chagua Wilaya</option>';
                                        districtData.data.forEach(d => {
                                            options += `<option value="${d.id}" ${d.id == v.district_id ? 'selected' : ''}>${d.name}</option>`;
                                        });
                                        $('#modalDistrictSelect').html(options).prop('disabled', false);

                                        // Load and set village
                                        fetch('api/get_locations.php?action=villages&district_id=' + v.district_id)
                                            .then(response => response.json())
                                            .then(villageData => {
                                                if (villageData.success) {
                                                    let vOptions = '<option value="">Select Village / Chagua Kijiji</option>';
                                                    villageData.data.forEach(vil => {
                                                        vOptions += `<option value="${vil.id}" ${vil.id == v.id ? 'selected' : ''}>${vil.name}</option>`;
                                                    });
                                                    $('#modalVillageId').html(vOptions).prop('disabled', false);
                                                }
                                            });
                                    }
                                });
                        }
                    });
            }

            $('#requestModal').modal('show');
        }

        // Region change - load districts
        $('#modalRegionSelect').on('change', function() {
            const regionId = $(this).val();
            const $district = $('#modalDistrictSelect');
            const $village = $('#modalVillageId');

            $district.prop('disabled', true).html('<option value="">Loading...</option>');
            $village.prop('disabled', true).html('<option value="">Select District first</option>');

            if (regionId) {
                fetch('api/get_locations.php?action=districts&region_id=' + regionId)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            let options = '<option value="">Select District / Chagua Wilaya</option>';
                            data.data.forEach(d => {
                                options += `<option value="${d.id}">${d.name}</option>`;
                            });
                            $district.html(options).prop('disabled', false);
                        }
                    });
            }
        });

        // District change - load villages
        $('#modalDistrictSelect').on('change', function() {
            const districtId = $(this).val();
            const $village = $('#modalVillageId');

            $village.prop('disabled', true).html('<option value="">Loading...</option>');

            if (districtId) {
                fetch('api/get_locations.php?action=villages&district_id=' + districtId)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            let options = '<option value="">Select Village / Chagua Kijiji</option>';
                            data.data.forEach(v => {
                                options += `<option value="${v.id}">${v.name}</option>`;
                            });
                            $village.html(options).prop('disabled', false);
                        }
                    });
            }
        });
    </script>
</body>
</html>
