<?php
include("../../../include/startup.php"); 
if (isset($_REQUEST['action'])) {
    while (ob_get_level()) {
        ob_end_clean(); 
    }
    header('Content-Type: application/json');
    header('Cache-Control: no-cache, must-revalidate');
}

if (!isset($_POST['clock_no']) || trim($_POST['clock_no']) === '') {
    echo json_encode(['status' => 'empty']);
    exit;
}

$clock_no = trim($_POST['clock_no']);
$sql = "SELECT * FROM admin WHERE clock_no = '$clock_no'";
$result = $conn->query($sql);

if ($result->num_rows === 0) {
    echo json_encode(['status' => 'invalid']);
    exit;
}

$user    = $result->fetch_assoc();
$user_id = $user['id'];

// Check for an active shift
$sql    = "SELECT * FROM shifts WHERE user_id = $user_id AND status = 'active'";
$result = $conn->query($sql);

if ($result->num_rows === 0) {
    // No active shift — user needs to clock in
    echo json_encode(['status' => 'none']);
    exit;
}

$shift    = $result->fetch_assoc();
$shift_id = $shift['id'];

// Check if shift is currently paused (open transaction with no pause_end)
$sql    = "SELECT * FROM transactions WHERE shift_id = $shift_id AND status = 'active' AND pause_end IS NULL";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Running — can pause or end
    echo json_encode(['status' => 'active']);
} else {
    // Check if there is any transaction at all (paused state)
    $sql    = "SELECT * FROM transactions WHERE shift_id = $shift_id AND status = 'active'";
    $result = $conn->query($sql);
    if ($result->num_rows > 0) {
        echo json_encode(['status' => 'paused']);
    } else {
        // Shift active, no transactions yet — still running
        echo json_encode(['status' => 'active']);
    }
}
