<?php
// db/staff-clock.php
ob_start();
ob_clean();
require_once '../core/api.php';

header('Content-Type: application/json');
$input = json_decode(file_get_contents('php://input'), true);

try {
    if (!isset($input['staff_id']) || !isset($input['action'])) {
        throw new Exception("Datos incompletos");
    }

    $staff_id = (int)$input['staff_id'];
    $action = $input['action']; 

    // 1. CONSULTAR ESTADO
    if ($action === 'check_status') {
        $stmt = $pdo->prepare("SELECT id, clock_in FROM work_logs WHERE staff_id = ? AND clock_out IS NULL ORDER BY id DESC LIMIT 1");
        $stmt->execute([$staff_id]);
        $current = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($current) {
            echo json_encode(['success' => true, 'status' => 'working', 'start_time' => $current['clock_in']]);
        } else {
            echo json_encode(['success' => true, 'status' => 'offline']);
        }
    }

    // 2. MARCAR ENTRADA
    elseif ($action === 'clock_in') {
        $check = $pdo->prepare("SELECT id FROM work_logs WHERE staff_id = ? AND clock_out IS NULL");
        $check->execute([$staff_id]);
        if ($check->fetch()) throw new Exception("Ya tienes un turno abierto.");

        $stmt = $pdo->prepare("INSERT INTO work_logs (staff_id, clock_in, created_at) VALUES (?, NOW(), NOW())");
        $stmt->execute([$staff_id]);
        
        echo json_encode(['success' => true, 'message' => 'Entrada registrada.']);
    }

    // 3. MARCAR SALIDA
    elseif ($action === 'clock_out') {
        $stmtGet = $pdo->prepare("SELECT id, clock_in FROM work_logs WHERE staff_id = ? AND clock_out IS NULL ORDER BY id DESC LIMIT 1");
        $stmtGet->execute([$staff_id]);
        $openLog = $stmtGet->fetch(PDO::FETCH_ASSOC);

        if (!$openLog) throw new Exception("No tienes un turno abierto.");

        $stmtUpd = $pdo->prepare("UPDATE work_logs SET clock_out = NOW() WHERE id = ?");
        $stmtUpd->execute([$openLog['id']]);

        echo json_encode(['success' => true, 'message' => 'Salida registrada.']);
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>