<?php
header('Content-Type: application/json');
include '../koneksi.php';

$id_wali    = $_POST['id_wali'] ?? '';
$tanggal    = $_POST['tanggal'] ?? '';
$kegiatan   = $_POST['kegiatan'] ?? '';
$hasil      = $_POST['hasil_tindak_lanjut'] ?? '';
$kesimpulan = $_POST['kesimpulan_saran'] ?? '';
$penutup    = $_POST['penutup'] ?? '';
$tipe       = $_POST['tipe'] ?? 'Individu';
$id_anak    = $_POST['id_anak'] ?? NULL;

$f1 = $_POST['foto1'] ?? '';
$f2 = $_POST['foto2'] ?? '';
$f3 = $_POST['foto3'] ?? '';

function uploadFoto($base64, $prefix) {
    if (empty($base64)) return "";
    $folder = "../images/img_wali/"; // PERBAIKAN PATH
    if (!file_exists($folder)) { mkdir($folder, 0777, true); }
    
    $nama = $prefix . "_" . time() . "_" . rand(10,99) . ".jpg";
    file_put_contents($folder . $nama, base64_decode(str_replace(' ', '+', $base64)));
    return $nama;
}

$nama_f1 = uploadFoto($f1, "W1");
$nama_f2 = uploadFoto($f2, "W2");
$nama_f3 = uploadFoto($f3, "W3");

$sql = "INSERT INTO laporan_wali (id_wali, tanggal, kegiatan, hasil_tindak_lanjut, kesimpulan_saran, penutup, tipe, id_anak, foto1, foto2, foto3) 
        VALUES ('$id_wali', '$tanggal', '$kegiatan', '$hasil', '$kesimpulan', '$penutup', '$tipe', " . ($id_anak ? "'$id_anak'" : "NULL") . ", '$nama_f1', '$nama_f2', '$nama_f3')";

if (mysqli_query($koneksi, $sql)) {
    echo json_encode(["status" => true, "message" => "Berhasil"]);
} else {
    echo json_encode(["status" => false, "message" => mysqli_error($koneksi)]);
}
?>