<?php
require_once '../config/config.php';
requireRole('secretariat');

$pageTitle = 'Walk-in Registration - Secretariat - PSAU GAD';
$db = getDB();

// Get activity ID from URL
$activityId = isset($_GET['activity_id']) ? (int)$_GET['activity_id'] : 0;

// Get activity details
if ($activityId) {
    $stmt = $db->prepare("SELECT * FROM activities WHERE activity_id = ?");
    $stmt->execute([$activityId]);
    $activity = $stmt->fetch();
    
    if (!$activity) {
        $_SESSION['error'] = 'Activity not found.';
        header('Location: attendance.php');
        exit;
    }
}

// Get all approved employees for dropdown
$stmt = $db->query("
    SELECT u.user_id, u.email, ep.first_name, ep.last_name, ep.category, ep.gender
    FROM users u
    JOIN employee_profiles ep ON u.user_id = ep.user_id
    WHERE u.role = 'employee' AND u.is_approved = 1 AND u.is_active = 1
    ORDER BY ep.last_name, ep.first_name
");
$employees = $stmt->fetchAll();

// Handle walk-in registration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['register_walkin'])) {
    $userId = (int)$_POST['user_id'];
    $activityId = (int)$_POST['activity_id'];
    $notes = trim($_POST['notes'] ?? '');
    
    try {
        $db->beginTransaction();
        
        // Check if already registered
        $stmt = $db->prepare("SELECT registration_id FROM activity_registrations WHERE activity_id = ? AND user_id = ?");
        $stmt->execute([$activityId, $userId]);
        $existingReg = $stmt->fetch();
        
        if ($existingReg) {
            $registrationId = $existingReg['registration_id'];
        } else {
            // Create registration
            $stmt = $db->prepare("
                INSERT INTO activity_registrations (activity_id, user_id, registration_date, status, is_approved, approved_by, approved_at)
                VALUES (?, ?, NOW(), 'approved', 1, ?, NOW())
            ");
            $stmt->execute([$activityId, $userId, getCurrentUserId()]);
            $registrationId = $db->lastInsertId();
            
            // Generate QR code
            $qrCodeFilename = "qr_{$activityId}_{$registrationId}_" . time() . ".png";
            $qrCodeUrl = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=REG-{$registrationId}";
            $qrCodePath = BASE_PATH . "/uploads/qr_codes/" . $qrCodeFilename;
            
            if (file_put_contents($qrCodePath, file_get_contents($qrCodeUrl))) {
                $stmt = $db->prepare("UPDATE activity_registrations SET qr_code = ?, qr_code_generated_at = NOW() WHERE registration_id = ?");
                $stmt->execute([$qrCodeFilename, $registrationId]);
            }
        }
        
        // Check if already attended
        $stmt = $db->prepare("SELECT attendance_id FROM activity_attendance WHERE registration_id = ?");
        $stmt->execute([$registrationId]);
        $existingAttendance = $stmt->fetch();
        
        if ($existingAttendance) {
            throw new Exception('This employee has already been marked as attended.');
        }
        
        // Mark attendance
        $activityStartTime = strtotime($activity['activity_date'] . ' ' . $activity['start_time']);
        $currentTime = time();
        $gracePeriod = ATTENDANCE_GRACE_PERIOD * 60; // Convert to seconds
        
        $status = ($currentTime <= ($activityStartTime + $gracePeriod)) ? 'present' : 'late';
        
        $stmt = $db->prepare("
            INSERT INTO activity_attendance (activity_id, user_id, registration_id, attendance_type, check_in_time, status, scanned_by, notes)
            VALUES (?, ?, ?, 'walk_in', NOW(), ?, ?, ?)
        ");
        $stmt->execute([$activityId, $userId, $registrationId, $status, getCurrentUserId(), $notes]);
        
        $db->commit();
        
        $_SESSION['success'] = 'Walk-in registration successful! Employee marked as ' . strtoupper($status) . '.';
        header('Location: attendance-walkin.php?activity_id=' . $activityId);
        exit;
        
    } catch (Exception $e) {
        $db->rollBack();
        $_SESSION['error'] = 'Error: ' . $e->getMessage();
    }
}

include '../includes/header.php';
include '../includes/navbar.php';
?>

<div class="min-h-screen bg-gray-50 py-8">
    <div class="container mx-auto px-4">
        <!-- Header -->
        <div class="mb-8">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-user-plus text-secretariat mr-2"></i>Walk-in Registration
                    </h1>
                    <p class="text-gray-600">Register employees on-site for activities</p>
                </div>
                <a href="attendance.php" class="bg-gray-500 text-white px-6 py-3 rounded-lg hover:bg-gray-600 transition font-semibold">
                    <i class="fas fa-arrow-left mr-2"></i>Back to Attendance
                </a>
            </div>
        </div>

        <?php if (isset($_SESSION['success'])): ?>
            <div class="bg-green-50 border border-green-200 text-green-800 px-6 py-4 rounded-lg mb-6">
                <i class="fas fa-check-circle mr-2"></i><?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="bg-red-50 border border-red-200 text-red-800 px-6 py-4 rounded-lg mb-6">
                <i class="fas fa-exclamation-circle mr-2"></i><?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
            </div>
        <?php endif; ?>

        <?php if ($activityId && $activity): ?>
            <!-- Activity Info -->
            <div class="bg-white rounded-xl shadow-lg p-6 mb-8 border-l-4 border-secretariat">
                <h2 class="text-xl font-bold text-gray-900 mb-4">
                    <i class="fas fa-calendar-alt text-secretariat mr-2"></i>Activity Information
                </h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <p class="text-sm text-gray-500">Activity Title</p>
                        <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($activity['title']); ?></p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Category</p>
                        <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($activity['category']); ?></p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Date</p>
                        <p class="font-semibold text-gray-900"><?php echo formatDate($activity['activity_date']); ?></p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Time</p>
                        <p class="font-semibold text-gray-900"><?php echo formatTime($activity['start_time']) . ' - ' . formatTime($activity['end_time']); ?></p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Venue</p>
                        <p class="font-semibold text-gray-900"><?php echo htmlspecialchars($activity['venue']); ?></p>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Grace Period</p>
                        <p class="font-semibold text-gray-900"><?php echo ATTENDANCE_GRACE_PERIOD; ?> minutes (Present) / After (Late)</p>
                    </div>
                </div>
            </div>

            <!-- Walk-in Registration Form -->
            <div class="bg-white rounded-xl shadow-lg p-8">
                <h2 class="text-2xl font-bold text-gray-900 mb-6">
                    <i class="fas fa-user-check text-secretariat mr-2"></i>Register Walk-in Participant
                </h2>

                <form method="POST" action="" class="space-y-6">
                    <input type="hidden" name="activity_id" value="<?php echo $activityId; ?>">

                    <!-- Employee Selection -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-user mr-2 text-secretariat"></i>Select Employee *
                        </label>
                        <select name="user_id" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent">
                            <option value="">-- Select Employee --</option>
                            <?php foreach ($employees as $emp): ?>
                                <option value="<?php echo $emp['user_id']; ?>">
                                    <?php echo htmlspecialchars($emp['last_name'] . ', ' . $emp['first_name']); ?> 
                                    (<?php echo htmlspecialchars($emp['category']); ?> - <?php echo htmlspecialchars($emp['gender']); ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <p class="text-sm text-gray-500 mt-1">Search by typing the employee's name</p>
                    </div>

                    <!-- Notes -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-sticky-note mr-2 text-secretariat"></i>Notes (Optional)
                        </label>
                        <textarea name="notes" rows="3" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-secretariat focus:border-transparent" placeholder="Any additional notes..."></textarea>
                    </div>

                    <!-- Info Box -->
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <h3 class="font-semibold text-blue-900 mb-2">
                            <i class="fas fa-info-circle mr-2"></i>What happens when you submit:
                        </h3>
                        <ul class="text-sm text-blue-800 space-y-1 ml-6 list-disc">
                            <li>Employee will be registered for this activity (if not already)</li>
                            <li>Registration will be auto-approved</li>
                            <li>QR code will be generated (if needed)</li>
                            <li>Attendance will be marked immediately</li>
                            <li>Status will be "Present" if within grace period, otherwise "Late"</li>
                        </ul>
                    </div>

                    <!-- Submit Button -->
                    <div class="flex gap-4">
                        <button type="submit" name="register_walkin" class="flex-1 bg-secretariat text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition font-semibold">
                            <i class="fas fa-check mr-2"></i>Register & Mark Attendance
                        </button>
                        <a href="attendance.php" class="bg-gray-500 text-white px-6 py-3 rounded-lg hover:bg-gray-600 transition font-semibold">
                            <i class="fas fa-times mr-2"></i>Cancel
                        </a>
                    </div>
                </form>
            </div>

        <?php else: ?>
            <!-- No Activity Selected -->
            <div class="bg-white rounded-xl shadow-lg p-12 text-center">
                <i class="fas fa-calendar-times text-gray-300 text-6xl mb-4"></i>
                <h3 class="text-xl font-bold text-gray-900 mb-2">No Activity Selected</h3>
                <p class="text-gray-600 mb-6">Please select an activity from the attendance page to register walk-in participants.</p>
                <a href="attendance.php" class="inline-block bg-secretariat text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition font-semibold">
                    <i class="fas fa-arrow-left mr-2"></i>Go to Attendance
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Select2 for better dropdown search -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize Select2 for better search
    $('select[name="user_id"]').select2({
        placeholder: '-- Select Employee --',
        allowClear: true,
        width: '100%'
    });
});
</script>

<?php include '../includes/footer.php'; ?>

