<?php
// status.php (updated to account for occurrences)
require_once 'config/database.php';
require_once 'utils/helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Helpers::sendResponse(false, 'Method not allowed', null, 405);
}

try {

    // auth
    $token = Helpers::getBearerToken();
    $userData = Helpers::verifyJWT($token);
    if (!$userData) Helpers::sendResponse(false, 'Unauthorized', null, 401);

    $database = new Database();
    $db = $database->getConnection();

    // Determine if DB uses service_occurrence_id in attendance
    $useOccurrenceColumn = false;
    $colCheck = $db->query("SHOW COLUMNS FROM `attendance` LIKE 'service_occurrence_id'");
    if ($colCheck && $colCheck->rowCount() > 0) $useOccurrenceColumn = true;

    // Query for today's most recent attendance for the user
    if ($useOccurrenceColumn) {
        // find latest attendance for today (if occurrence_id present we can check occurrence date too)
        $query = "SELECT a.id, a.service_occurrence_id AS occurrence_id, a.clock_in_time, a.clock_out_time, a.time_spent,
                     oc.start_time, oc.end_time, st.name AS service_name
              FROM attendance a
              LEFT JOIN service_occurrences oc ON a.service_occurrence_id = oc.id
              LEFT JOIN service_templates st ON oc.service_template_id = st.id
              WHERE a.user_id = :user_id
              AND DATE(a.clock_in_time) = CURDATE()
              ORDER BY a.clock_in_time DESC
              LIMIT 1";
    } else {
        $query = "SELECT a.id, a.service_id, a.clock_in_time, a.clock_out_time, a.time_spent,
                     s.name AS service_name
              FROM attendance a
              LEFT JOIN services s ON a.service_id = s.id
              WHERE a.user_id = :user_id
              AND DATE(a.clock_in_time) = CURDATE()
              ORDER BY a.clock_in_time DESC
              LIMIT 1";
    }

    $stmt = $db->prepare($query);
    $stmt->bindParam(':user_id', $userData['user_id']);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        $attendance = $stmt->fetch();
        Helpers::sendResponse(true, 'Attendance status retrieved', [
            'id' => $attendance['id'],
            'service_label' => $attendance['service_name'] ?? ($attendance['occurrence_id'] ?? $attendance['service_id'] ?? null),
            'clock_in_time' => $attendance['clock_in_time'],
            'clock_out_time' => $attendance['clock_out_time'],
            'time_spent' => $attendance['time_spent'],
            'clocked_in' => true,
            'clocked_out' => !empty($attendance['clock_out_time'])
        ]);
    } else {
        Helpers::sendResponse(true, 'No attendance today', [
            'clocked_in' => false,
            'clocked_out' => false
        ]);
    }
} catch (PDOException $e) {
    ErrorLogger::logDatabaseError($e, $userData['user_id'] ?? 'unknown', [
        'endpoint' => 'user/status',
        'user_id' => $userData['user_id'] ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'Database error occurred: ' . $e->getMessage(), null, 500);
} catch (Exception $e) {
    ErrorLogger::logError($e, [
        'endpoint' => 'user/status',
        'user_id' => $userData['user_id'] ?? 'unknown'
    ]);
    Helpers::sendResponse(false, $e->getMessage(), null, 500);
}
