<?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);
$student_id_input = $input['student_id'] ?? '';

if (empty($student_id_input)) {
    $response['message'] = 'Student ID is required';
    echo json_encode($response);
    exit();
}

// Get student by student ID
$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.student_id = '" . escape($conn, $student_id_input) . "' AND s.status = 1";
$result = query($conn, $sql);

if (!$result || mysqli_num_rows($result) === 0) {
    $response['message'] = 'Student not found with ID: ' . $student_id_input;
    echo json_encode($response);
    exit();
}

$student = mysqli_fetch_assoc($result);

// Get current time and date
$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) {
    $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'] . ", 
                        'Manual entry - 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'),
            'action' => 'time_out'
        ];
    }
} else {
    // Create new attendance record
    $time_in = date('Y-m-d H:i:s');
    $status = 'present';
    
    // Check if late
    $activity_start = strtotime($activity['date'] . ' ' . $activity['time_in']);
    $current_timestamp = time();
    
    if (($current_timestamp - $activity_start) > 900) {
        $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'] . ", 
                        'Manual entry - 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);
?>