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

date_default_timezone_set('Asia/Baghdad'); // Iraqi local time

$settings_res = $conn->query("SELECT workday_start_hour FROM system_settings WHERE id = 1");
$start_hour = 17; // default to 5:00 PM if not configured
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');

// Fetch materials for current shift
$stmt = $conn->prepare("
    SELECT m.*, COALESCE(g.name, '') AS jallab_name
    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();
$materials_res = $stmt->get_result();
$materials = [];
while ($row = $materials_res->fetch_assoc()) {
    $materials[] = $row;
}
$stmt->close();

// Strictly return materials registered for the current shift/today only
echo json_encode([
    'status' => 'success',
    'materials' => $materials
]);
?>
