<?php
/**
 * Verification Requests
 * Village officials can view and manage land verification requests
 */

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_id = $_SESSION['user_id'];
$user_role = $_SESSION['role'];
$village_id = $_SESSION['village_id'] ?? null;

$message = '';
$error = '';

// Handle actions
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $request_id = intval($_POST['request_id']);
    $action = $_POST['action'];

    // Verify request exists and belongs to this village
    $req_check = mysqli_query($conn, "SELECT * FROM verification_requests WHERE id = $request_id");
    $request = mysqli_fetch_assoc($req_check);

    if($request) {
        if($action == 'accept') {
            mysqli_query($conn, "UPDATE verification_requests SET
                status = 'in_progress',
                assigned_to = $user_id,
                assigned_at = NOW()
                WHERE id = $request_id");

            // Update land status
            mysqli_query($conn, "UPDATE lands SET status = 'pending_village' WHERE id = {$request['land_id']}");

            // Notify user
            mysqli_query($conn, "INSERT INTO cbc_notifications (
                user_id, notification_type, title, message, land_id, created_at
            ) VALUES (
                {$request['user_id']}, 'village_review_pending',
                'Verification Request Accepted',
                'Your verification request #{$request['request_number']} has been accepted and is being processed.',
                {$request['land_id']}, NOW()
            )");

            $message = 'Request accepted and assigned to you.';

        } elseif($action == 'complete') {
            $response_notes = mysqli_real_escape_string($conn, trim($_POST['response_notes'] ?? ''));

            mysqli_query($conn, "UPDATE verification_requests SET
                status = 'completed',
                response_notes = '$response_notes',
                responded_by = $user_id,
                responded_at = NOW()
                WHERE id = $request_id");

            // Update land status to village_verified
            mysqli_query($conn, "UPDATE lands SET
                status = 'village_verified',
                village_verified_by = $user_id,
                village_verified_at = NOW()
                WHERE id = {$request['land_id']}");

            // Log history
            mysqli_query($conn, "INSERT INTO land_history (
                land_id, event_type, event_description, performed_by, performed_by_role
            ) VALUES (
                {$request['land_id']}, 'village_approved',
                'Land verified by village official',
                $user_id, '$user_role'
            )");

            // Notify user
            mysqli_query($conn, "INSERT INTO cbc_notifications (
                user_id, notification_type, title, message, land_id, created_at
            ) VALUES (
                {$request['user_id']}, 'village_approved',
                'Land Verified by Village',
                'Congratulations! Your land has been verified by village officials. It is now pending professional survey.',
                {$request['land_id']}, NOW()
            )");

            $message = 'Verification completed successfully.';

        } elseif($action == 'reject') {
            $response_notes = mysqli_real_escape_string($conn, trim($_POST['response_notes'] ?? ''));

            mysqli_query($conn, "UPDATE verification_requests SET
                status = 'rejected',
                response_notes = '$response_notes',
                responded_by = $user_id,
                responded_at = NOW()
                WHERE id = $request_id");

            // Update land status
            mysqli_query($conn, "UPDATE lands SET
                status = 'rejected',
                village_rejection_reason = '$response_notes'
                WHERE id = {$request['land_id']}");

            // Notify user
            mysqli_query($conn, "INSERT INTO cbc_notifications (
                user_id, notification_type, title, message, land_id, created_at
            ) VALUES (
                {$request['user_id']}, 'village_rejected',
                'Verification Request Rejected',
                'Your verification request has been rejected. Reason: $response_notes',
                {$request['land_id']}, NOW()
            )");

            $message = 'Request rejected.';
        }
    }
}

// Build WHERE clause
$where = "1=1";
if($user_role !== 'district_officer' && $village_id) {
    $where .= " AND vr.village_id = $village_id";
}

// Filter
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'pending';
if($filter == 'pending') {
    $where .= " AND vr.status = 'pending'";
} elseif($filter == 'in_progress') {
    $where .= " AND vr.status = 'in_progress'";
} elseif($filter == 'completed') {
    $where .= " AND vr.status = 'completed'";
} elseif($filter == 'rejected') {
    $where .= " AND vr.status = 'rejected'";
}

// Get requests
$requests = mysqli_query($conn, "
    SELECT vr.*,
           l.land_name, l.total_area, l.area_unit,
           u.full_name as owner_name, u.phone as owner_phone, u.email as owner_email,
           v.name as village_name,
           a.full_name as assigned_to_name
    FROM verification_requests vr
    JOIN lands l ON vr.land_id = l.id
    JOIN users u ON vr.user_id = u.id
    LEFT JOIN villages v ON vr.village_id = v.id
    LEFT JOIN users a ON vr.assigned_to = a.id
    WHERE $where
    ORDER BY vr.created_at DESC
");

// Get counts
$pending_count = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as c FROM verification_requests vr WHERE " . ($village_id ? "vr.village_id = $village_id AND " : "") . "vr.status = 'pending'"))['c'];
$progress_count = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as c FROM verification_requests vr WHERE " . ($village_id ? "vr.village_id = $village_id AND " : "") . "vr.status = 'in_progress'"))['c'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verification Requests - Land Secure CBC</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 { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 16px; }
        .page-header h1 { font-size: 24px; font-weight: 700; color: #1a1d21; display: flex; align-items: center; gap: 12px; margin: 0; }
        .page-header h1 i { color: #11998e; }
        .page-header p { color: #64748b; margin: 8px 0 0; }

        .filter-tabs { display: flex; gap: 10px; margin-bottom: 24px; flex-wrap: wrap; }
        .filter-tab {
            display: flex; align-items: center; gap: 8px;
            padding: 10px 18px; background: white; border-radius: 12px;
            text-decoration: none; color: #64748b; font-weight: 500; font-size: 14px;
            transition: all 0.3s; box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        }
        .filter-tab:hover { background: #f8fafc; color: #11998e; text-decoration: none; }
        .filter-tab.active { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; }
        .filter-tab .badge { background: rgba(255,255,255,0.2); padding: 4px 10px; border-radius: 20px; font-size: 11px; }

        .alert { border: none; border-radius: 14px; padding: 16px 20px; margin-bottom: 24px; }
        .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; }

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

        .request-card {
            background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            overflow: hidden; border-left: 4px solid #11998e;
        }
        .request-card.status-in_progress { border-left-color: #f59e0b; }
        .request-card.status-completed { border-left-color: #22c55e; }
        .request-card.status-rejected { border-left-color: #ef4444; }

        .request-header { padding: 20px; background: #f8fafc; border-bottom: 1px solid #e2e8f0; }
        .request-number { font-size: 12px; color: #64748b; font-weight: 600; margin-bottom: 4px; }
        .request-title { font-size: 18px; font-weight: 600; color: #1a1d21; margin: 0; }

        .request-body { padding: 20px; }
        .owner-row { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px solid #f0f2f5; }
        .owner-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; font-size: 18px; }
        .owner-info h4 { font-size: 15px; font-weight: 600; color: #1a1d21; margin: 0 0 4px; }
        .owner-info p { font-size: 13px; color: #64748b; margin: 0; }

        .request-meta { display: flex; flex-wrap: wrap; gap: 16px; font-size: 13px; color: #64748b; margin-bottom: 16px; }
        .request-meta span { display: flex; align-items: center; gap: 6px; }

        .request-notes { background: #f8fafc; padding: 12px 16px; border-radius: 10px; font-size: 13px; color: #475569; margin-bottom: 16px; }
        .request-notes strong { display: block; font-size: 12px; color: #64748b; margin-bottom: 4px; }

        .status-badge { padding: 6px 14px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .status-pending { background: #fef3c7; color: #d97706; }
        .status-in_progress { background: #dbeafe; color: #2563eb; }
        .status-completed { background: #d1fae5; color: #059669; }
        .status-rejected { background: #fee2e2; color: #dc2626; }

        .request-actions { padding: 16px 20px; background: #f8fafc; display: flex; gap: 10px; flex-wrap: wrap; }
        .btn { flex: 1; padding: 10px 16px; border-radius: 8px; font-size: 13px; font-weight: 600; text-align: center; text-decoration: none; transition: all 0.2s; border: none; cursor: pointer; }
        .btn-primary { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; }
        .btn-success { background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); color: white; }
        .btn-danger { background: linear-gradient(135deg, #ef4444 0%, #dc2626 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: #22c55e; margin-bottom: 16px; }

        .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; }
        .form-control { border-radius: 10px; border: 2px solid #e2e8f0; padding: 12px 16px; }
        .form-control:focus { border-color: #11998e; box-shadow: 0 0 0 4px rgba(17, 153, 142, 0.1); }

        @media (max-width: 768px) { .requests-grid { grid-template-columns: 1fr; } }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <div class="page-header">
            <div>
                <h1><i class="fas fa-clipboard-list"></i> Verification Requests</h1>
                <p>Maombi ya Uhakiki / Land verification requests from landowners</p>
            </div>
        </div>

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

        <div class="filter-tabs">
            <a href="verification_requests?filter=pending" class="filter-tab <?php echo $filter == 'pending' ? 'active' : ''; ?>">
                <i class="fas fa-clock"></i> Pending
                <?php if($pending_count > 0): ?><span class="badge"><?php echo $pending_count; ?></span><?php endif; ?>
            </a>
            <a href="verification_requests?filter=in_progress" class="filter-tab <?php echo $filter == 'in_progress' ? 'active' : ''; ?>">
                <i class="fas fa-spinner"></i> In Progress
                <?php if($progress_count > 0): ?><span class="badge"><?php echo $progress_count; ?></span><?php endif; ?>
            </a>
            <a href="verification_requests?filter=completed" class="filter-tab <?php echo $filter == 'completed' ? 'active' : ''; ?>">
                <i class="fas fa-check"></i> Completed
            </a>
            <a href="verification_requests?filter=rejected" class="filter-tab <?php echo $filter == 'rejected' ? 'active' : ''; ?>">
                <i class="fas fa-times"></i> Rejected
            </a>
            <a href="verification_requests?filter=all" class="filter-tab <?php echo $filter == 'all' ? 'active' : ''; ?>">
                <i class="fas fa-list"></i> All
            </a>
        </div>

        <?php if(mysqli_num_rows($requests) > 0): ?>
        <div class="requests-grid">
            <?php while($req = mysqli_fetch_assoc($requests)): ?>
            <div class="request-card status-<?php echo $req['status']; ?>">
                <div class="request-header">
                    <div class="request-number">#<?php echo htmlspecialchars($req['request_number']); ?></div>
                    <h3 class="request-title"><?php echo htmlspecialchars($req['land_name']); ?></h3>
                </div>
                <div class="request-body">
                    <div class="owner-row">
                        <div class="owner-avatar"><?php echo strtoupper(substr($req['owner_name'], 0, 1)); ?></div>
                        <div class="owner-info">
                            <h4><?php echo htmlspecialchars($req['owner_name']); ?></h4>
                            <p><i class="fas fa-phone"></i> <?php echo htmlspecialchars($req['owner_phone']); ?></p>
                        </div>
                    </div>
                    <div class="request-meta">
                        <span><i class="fas fa-calendar"></i> <?php echo date('M d, Y', strtotime($req['created_at'])); ?></span>
                        <span><i class="fas fa-ruler-combined"></i> <?php echo number_format($req['total_area'], 2); ?> <?php echo $req['area_unit']; ?></span>
                        <?php if($req['village_name']): ?>
                        <span><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($req['village_name']); ?></span>
                        <?php endif; ?>
                    </div>
                    <?php if($req['notes']): ?>
                    <div class="request-notes">
                        <strong>Notes from Owner:</strong>
                        <?php echo htmlspecialchars($req['notes']); ?>
                    </div>
                    <?php endif; ?>
                    <span class="status-badge status-<?php echo $req['status']; ?>">
                        <?php echo ucfirst(str_replace('_', ' ', $req['status'])); ?>
                    </span>
                    <?php if($req['assigned_to_name']): ?>
                    <p style="margin-top: 10px; font-size: 12px; color: #64748b;">
                        <i class="fas fa-user"></i> Assigned to: <?php echo htmlspecialchars($req['assigned_to_name']); ?>
                    </p>
                    <?php endif; ?>
                </div>
                <div class="request-actions">
                    <?php if($req['status'] == 'pending'): ?>
                    <form method="POST" style="flex: 1;">
                        <input type="hidden" name="request_id" value="<?php echo $req['id']; ?>">
                        <input type="hidden" name="action" value="accept">
                        <button type="submit" class="btn btn-primary" style="width: 100%;">
                            <i class="fas fa-check"></i> Accept & Assign to Me
                        </button>
                    </form>
                    <?php elseif($req['status'] == 'in_progress'): ?>
                    <a href="verify_land?id=<?php echo $req['land_id']; ?>" class="btn btn-primary">
                        <i class="fas fa-eye"></i> Review Land
                    </a>
                    <button type="button" class="btn btn-success" onclick="openCompleteModal(<?php echo $req['id']; ?>, '<?php echo addslashes($req['land_name']); ?>')">
                        <i class="fas fa-check-double"></i> Complete
                    </button>
                    <button type="button" class="btn btn-danger" onclick="openRejectModal(<?php echo $req['id']; ?>, '<?php echo addslashes($req['land_name']); ?>')">
                        <i class="fas fa-times"></i> Reject
                    </button>
                    <?php else: ?>
                    <a href="verify_land?id=<?php echo $req['land_id']; ?>" class="btn btn-outline" style="width: 100%;">
                        <i class="fas fa-eye"></i> View Land Details
                    </a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
        <?php else: ?>
        <div class="empty-state">
            <i class="fas fa-inbox"></i>
            <h3>No Requests Found</h3>
            <p>Hakuna maombi <?php echo $filter != 'all' ? '(' . $filter . ')' : ''; ?></p>
        </div>
        <?php endif; ?>
    </main>

    <!-- Complete Modal -->
    <div class="modal fade" id="completeModal" 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-check-double"></i> Complete Verification</h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="request_id" id="completeRequestId">
                        <input type="hidden" name="action" value="complete">
                        <p>You are about to mark <strong id="completeLandName"></strong> as verified.</p>
                        <div class="form-group">
                            <label>Verification Notes (Optional)</label>
                            <textarea name="response_notes" class="form-control" rows="3"
                                placeholder="Any notes about the verification..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">Complete Verification</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Reject Modal -->
    <div class="modal fade" id="rejectModal" 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-times-circle"></i> Reject Verification</h5>
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="request_id" id="rejectRequestId">
                        <input type="hidden" name="action" value="reject">
                        <p>You are about to reject verification for <strong id="rejectLandName"></strong>.</p>
                        <div class="form-group">
                            <label>Reason for Rejection <span style="color: #ef4444;">*</span></label>
                            <textarea name="response_notes" class="form-control" rows="3" required
                                placeholder="Please provide a reason for rejection..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Reject Request</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        function openCompleteModal(requestId, landName) {
            $('#completeRequestId').val(requestId);
            $('#completeLandName').text(landName);
            $('#completeModal').modal('show');
        }

        function openRejectModal(requestId, landName) {
            $('#rejectRequestId').val(requestId);
            $('#rejectLandName').text(landName);
            $('#rejectModal').modal('show');
        }
    </script>
</body>
</html>
