<?php
require_once '../includes/config.php';

header('Content-Type: application/json');

// Check if user is logged in
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

$response = [
    'success' => false,
    'message' => '',
    'data' => []
];

// Get input data
$input = json_decode(file_get_contents('php://input'), true);
$qr_code = $input['qr_code'] ?? '';

if (empty($qr_code)) {
    $response['message'] = 'QR code is required';
    echo json_encode($response);
    exit();
}

// Extract student ID from QR code (format: STU_23-0217_692b07dd55c31)
$qr_parts = explode('_', $qr_code);
if (count($qr_parts) < 3 || $qr_parts[0] !== 'STU') {
    $response['message'] = 'Invalid QR code format';
    echo json_encode($response);
    exit();
}

$student_id_str = $qr_parts[1]; // e.g., 23-0217

// Get student details
$sql = "SELECT s.*, c.code as course_code, d.name as department_name 
        FROM students s 
        JOIN courses c ON s.course_id = c.id 
        JOIN departments d ON s.department_id = d.id 
        WHERE s.qr_code = '" . escape($conn, $qr_code) . "' AND s.status = 1";
$result = query($conn, $sql);

if (!$result || mysqli_num_rows($result) === 0) {
    $response['message'] = 'Student not found or QR code invalid';
    echo json_encode($response);
    exit();
}

$student = mysqli_fetch_assoc($result);

// Get current time
$current_time = date('H:i:s');
$current_date = date('Y-m-d');

// Find active activity for the student
$activity_sql = "SELECT * FROM activities 
                WHERE status = 1 
                AND date = '$current_date' 
                AND time_in <= '$current_time' 
                AND time_out >= '$current_time' 
                AND (
                    required_students = 'all' 
                    OR (required_students = 'specific_course' AND course_id = " . $student['course_id'] . ")
                    OR (required_students = 'specific_department' AND department_id = " . $student['department_id'] . ")
                )
                LIMIT 1";

$activity_result = query($conn, $activity_sql);

if (!$activity_result || mysqli_num_rows($activity_result) === 0) {
    // If no current activity, check for any today's activity
    $activity_sql = "SELECT * FROM activities 
                    WHERE status = 1 
                    AND date = '$current_date'
                    ORDER BY time_in DESC 
                    LIMIT 1";
    $activity_result = query($conn, $activity_sql);
}

if (!$activity_result || mysqli_num_rows($activity_result) === 0) {
    $response['message'] = 'No active activity found for today';
    echo json_encode($response);
    exit();
}

$activity = mysqli_fetch_assoc($activity_result);

// Check if attendance already exists
$attendance_sql = "SELECT * FROM attendance 
                   WHERE student_id = " . $student['id'] . " 
                   AND activity_id = " . $activity['id'];
$attendance_result = query($conn, $attendance_sql);

if ($attendance_result && mysqli_num_rows($attendance_result) > 0) {
    // Update time out if already has time in
    $attendance = mysqli_fetch_assoc($attendance_result);
    
    if ($attendance['time_out']) {
        $response['message'] = 'Attendance already completed for this activity';
        echo json_encode($response);
        exit();
    }
    
    // Update time out
    $time_out = date('Y-m-d H:i:s');
    $update_sql = "UPDATE attendance 
                   SET time_out = '$time_out',
                       status = 'present',
                       updated_at = NOW()
                   WHERE id = " . $attendance['id'];
    
    if (query($conn, $update_sql)) {
        // Log the action
        $log_sql = "INSERT INTO attendance_logs 
                    (attendance_id, action, old_value, new_value, changed_by, notes) 
                    VALUES (
                        " . $attendance['id'] . ", 
                        'time_out', 
                        NULL, 
                        '$time_out', 
                        " . $_SESSION['user_id'] . ", 
                        'QR code scan - time out'
                    )";
        query($conn, $log_sql);
        
        $response['success'] = true;
        $response['message'] = 'Time out recorded successfully';
        $response['data'] = [
            'student_name' => $student['full_name'],
            'activity_name' => $activity['name'],
            'time' => date('h:i:s A'),
            'status' => 'present',
            'action' => 'time_out'
        ];
    }
} else {
    // Create new attendance record
    $time_in = date('Y-m-d H:i:s');
    $status = 'present';
    
    // Check if late (more than 15 minutes after activity start)
    $activity_start = strtotime($activity['date'] . ' ' . $activity['time_in']);
    $current_timestamp = time();
    
    if (($current_timestamp - $activity_start) > 900) { // 900 seconds = 15 minutes
        $status = 'late';
    }
    
    $insert_sql = "INSERT INTO attendance 
                   (student_id, activity_id, time_in, status, created_at, updated_at) 
                   VALUES (
                       " . $student['id'] . ", 
                       " . $activity['id'] . ", 
                       '$time_in', 
                       '$status', 
                       NOW(), 
                       NOW()
                   )";
    
    if (query($conn, $insert_sql)) {
        $attendance_id = getInsertId($conn);
        
        // Log the action
        $log_sql = "INSERT INTO attendance_logs 
                    (attendance_id, action, old_value, new_value, changed_by, notes) 
                    VALUES (
                        $attendance_id, 
                        'time_in', 
                        NULL, 
                        '$time_in', 
                        " . $_SESSION['user_id'] . ", 
                        'QR code scan - time in'
                    )";
        query($conn, $log_sql);
        
        $response['success'] = true;
        $response['message'] = 'Time in recorded successfully';
        $response['data'] = [
            'student_name' => $student['full_name'],
            'activity_name' => $activity['name'],
            'time' => date('h:i:s A'),
            'status' => $status,
            'action' => 'time_in'
        ];
    }
}

echo json_encode($response);
?>