<?php
declare(strict_types=1);

// modules/get_unit_activities.php
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');

ob_start();

require_once __DIR__ . '/../config/database.php';

header('Content-Type: application/json; charset=utf-8');

try {
    $conn = function_exists('getAppConnection') ? getAppConnection() : getConnection();

    if (!$conn) {
        throw new Exception('Koneksi database gagal');
    }

    $unit_id = isset($_GET['unit_id']) ? (int)$_GET['unit_id'] : 0;
    $date    = trim((string)($_GET['date'] ?? date('Y-m-d')));

    $activities = [];

    if ($unit_id > 0) {
        $stmt = $conn->prepare("
            SELECT *
            FROM daily_activities
            WHERE unit_id = ? AND activity_date = ?
            ORDER BY start_time, id
        ");

        if (!$stmt) {
            throw new Exception('Prepare query gagal: ' . $conn->error);
        }

        $stmt->bind_param("is", $unit_id, $date);
        $stmt->execute();
        $result = $stmt->get_result();

        while ($result && $row = $result->fetch_assoc()) {
            $activities[] = $row;
        }

        $stmt->close();
    }

    ob_clean();
    echo json_encode($activities, JSON_UNESCAPED_UNICODE);
    exit;

} catch (Throwable $e) {
    ob_clean();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'data' => []
    ], JSON_UNESCAPED_UNICODE);
    exit;
}