<?php
require_once 'db_pdo.php';
require_once 'auth.php';
require_once 'penduduk_feature_helper.php';
require_admin_login(true);
header('Content-Type: application/json');

$input = $_POST ?: (json_decode(file_get_contents('php://input'), true) ?: []);

if (empty($input['penduduk_id']) || empty($input['jenis_bantuan']) || empty($input['tanggal_bantuan'])) {
    echo json_encode(['success' => false, 'message' => 'Penduduk, jenis bantuan, dan tanggal wajib diisi.']);
    exit;
}

try {
    ensurePendudukFeatureSchema($pdo);
    $buktiFile = saveUploadedEvidence('bukti_file');

    $stmt = $pdo->prepare("
        INSERT INTO riwayat_bantuan (penduduk_id, jenis_bantuan, tanggal_bantuan, nilai_bantuan, pemberi_bantuan, catatan, bukti_file)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $input['penduduk_id'],
        $input['jenis_bantuan'],
        normalizeDateOrNull($input['tanggal_bantuan']) ?? date('Y-m-d'),
        $input['nilai_bantuan'] ?? null,
        $input['pemberi_bantuan'] ?? 'Admin',
        $input['catatan'] ?? null,
        $buktiFile,
    ]);

    $update = $pdo->prepare("
        UPDATE penduduk_miskin
        SET status_bantuan = 'Sudah dibantu', jenis_bantuan = ?, tanggal_bantuan = ?
        WHERE id = ?
    ");
    $update->execute([
        $input['jenis_bantuan'],
        normalizeDateOrNull($input['tanggal_bantuan']) ?? date('Y-m-d'),
        $input['penduduk_id'],
    ]);

    updatePendudukPriority($pdo, (int)$input['penduduk_id']);

    echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]);
} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
