<?php
declare(strict_types=1);

// modules/save_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');
    }

    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true);

    if (!is_array($data)) {
        throw new Exception('Payload JSON tidak valid');
    }

    $unit_id    = isset($data['unit_id']) ? (int)$data['unit_id'] : 0;
    $date       = trim((string)($data['date'] ?? ''));
    $activities = $data['activities'] ?? [];

    // karena auth dihapus, pakai default 0
    $created_by = 0;

    if ($unit_id <= 0 || $date === '') {
        throw new Exception('Data tidak lengkap');
    }

    if (!is_array($activities)) {
        throw new Exception('Format activities tidak valid');
    }

    $conn->begin_transaction();

    $stmtDelete = $conn->prepare("DELETE FROM daily_activities WHERE unit_id = ? AND activity_date = ?");
    if (!$stmtDelete) {
        throw new Exception('Prepare delete gagal: ' . $conn->error);
    }

    $stmtDelete->bind_param("is", $unit_id, $date);
    $stmtDelete->execute();
    $stmtDelete->close();

    $stmtInsert = $conn->prepare("
        INSERT INTO daily_activities
        (activity_date, unit_id, level, jenis_kegiatan, activity_name, start_time, end_time, description, created_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

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

    $inserted = 0;

    foreach ($activities as $act) {
        $level          = trim((string)($act['level'] ?? 'Perawat'));
        $jenis_kegiatan = trim((string)($act['jenis_kegiatan'] ?? 'lainnya'));
        $activity_name  = trim((string)($act['activity_name'] ?? ''));
        $start_time     = !empty($act['start_time']) ? trim((string)$act['start_time']) : null;
        $end_time       = !empty($act['end_time']) ? trim((string)$act['end_time']) : null;
        $description    = trim((string)($act['description'] ?? ''));

        if ($activity_name === '' && $description === '' && empty($start_time) && empty($end_time)) {
            continue;
        }

        $stmtInsert->bind_param(
            "sissssssi",
            $date,
            $unit_id,
            $level,
            $jenis_kegiatan,
            $activity_name,
            $start_time,
            $end_time,
            $description,
            $created_by
        );

        if (!$stmtInsert->execute()) {
            throw new Exception('Insert kegiatan gagal: ' . $stmtInsert->error);
        }

        $inserted++;
    }

    $stmtInsert->close();
    $conn->commit();

    ob_clean();
    echo json_encode([
        'success' => true,
        'inserted' => $inserted,
        'message' => 'Kegiatan berhasil disimpan'
    ], JSON_UNESCAPED_UNICODE);
    exit;

} catch (Throwable $e) {
    if (isset($conn) && $conn instanceof mysqli) {
        try {
            $conn->rollback();
        } catch (Throwable $rollbackError) {
        }
    }

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