<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/erp/config/database.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/erp/config/auth.php';
header('Content-Type: application/json');
requireRole('director', 'accountant', 'manager', 'production');

$pdo     = getDBConnection();
$userId  = (int)($_GET['user_id'] ?? 0);
$date    = $_GET['date'] ?? '';

if (!$userId || !$date) { echo json_encode([]); exit; }

// Chấm công
$att = $pdo->prepare("SELECT * FROM attendance_logs WHERE user_id=? AND work_date=?");
$att->execute([$userId, $date]);
$attData = $att->fetch() ?: null;

// OT
$ot = $pdo->prepare("SELECT * FROM overtime_requests WHERE user_id=? AND ot_date=? AND status='approved'");
$ot->execute([$userId, $date]);
$otData = $ot->fetch() ?: null;

// Nghỉ phép
$lv = $pdo->prepare("SELECT * FROM leave_requests WHERE user_id=? AND start_date<=? AND end_date>=? AND status='approved'");
$lv->execute([$userId, $date, $date]);
$lvData = $lv->fetch() ?: null;

// Ca làm việc
$sh = $pdo->prepare("
    SELECT ws.* FROM employee_shifts es
    JOIN work_shifts ws ON es.shift_id = ws.id
    WHERE es.user_id=? AND es.effective_date<=? AND (es.end_date IS NULL OR es.end_date>=?)
    ORDER BY es.effective_date DESC LIMIT 1
");
$sh->execute([$userId, $date, $date]);
$shData = $sh->fetch() ?: null;

echo json_encode(['att' => $attData, 'ot' => $otData, 'leave' => $lvData, 'shift' => $shData]);