<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../includes/db.php';

date_default_timezone_set('Asia/Baghdad');

$settings_res = $conn->query("SELECT workday_start_hour FROM system_settings WHERE id = 1");
$start_hour = 17;
if ($settings_res && $row = $settings_res->fetch_assoc()) {
    $start_hour = intval($row['workday_start_hour']);
}

$now = new DateTime();
$current_hour = (int)$now->format('H');

if ($current_hour >= $start_hour) {
    $start = clone $now;
    $start->setTime($start_hour, 0, 0);
    $end = clone $now;
    $end->modify('+1 day');
    $end->setTime($start_hour, 0, 0);
} else {
    $start = clone $now;
    $start->modify('-1 day');
    $start->setTime($start_hour, 0, 0);
    $end = clone $now;
    $end->setTime($start_hour, 0, 0);
}

$start_str = $start->format('Y-m-d H:i:s');
$end_str = $end->format('Y-m-d H:i:s');

$stmt = $conn->prepare("
    SELECT m.id, m.name, COALESCE(g.name, 'غير محدد') AS jallab_name, m.created_at
    FROM materials m
    LEFT JOIN gatherers g ON m.jallab_id = g.id
    WHERE m.created_at >= ? AND m.created_at < ?
    ORDER BY m.name ASC
");
$stmt->bind_param("ss", $start_str, $end_str);
$stmt->execute();
$res = $stmt->get_result();

$shift_materials = [];
while ($row = $res->fetch_assoc()) {
    $shift_materials[] = [
        'id' => (int)$row['id'],
        'name' => $row['name'],
        'jallab' => $row['jallab_name'],
        'created_at' => $row['created_at']
    ];
}
$stmt->close();

// Fallback: If no materials registered in current shift, load recent materials so list is never empty
$all_materials = [];
if (empty($shift_materials)) {
    $res_all = $conn->query("
        SELECT m.id, m.name, COALESCE(g.name, 'غير محدد') AS jallab_name, m.created_at
        FROM materials m
        LEFT JOIN gatherers g ON m.jallab_id = g.id
        ORDER BY m.id DESC
        LIMIT 100
    ");
    while ($row = $res_all->fetch_assoc()) {
        $all_materials[] = [
            'id' => (int)$row['id'],
            'name' => $row['name'],
            'jallab' => $row['jallab_name'],
            'created_at' => $row['created_at']
        ];
    }
}

echo json_encode([
    'status' => 'success',
    'start_hour' => $start_hour,
    'start_time' => $start_str,
    'end_time' => $end_str,
    'shift_materials_count' => count($shift_materials),
    'materials' => !empty($shift_materials) ? $shift_materials : $all_materials,
    'is_fallback' => empty($shift_materials)
], JSON_UNESCAPED_UNICODE);
?>
