<?php
session_start();
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'petugas'])) {
    header('Content-Type: application/json');
    http_response_code(403);
    echo json_encode(['status'=>'error','message'=>'Akses ditolak.']);
    exit;
}

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

$nama            = trim($_POST['nama']            ?? '');
$nik             = trim($_POST['nik']             ?? '');
$keterangan      = trim($_POST['keterangan']      ?? '');
$alamat          = trim($_POST['alamat']          ?? '');
$latitude        = trim($_POST['latitude']        ?? '');
$longitude       = trim($_POST['longitude']       ?? '');
$status_jangkauan= trim($_POST['status_jangkauan']?? 'Luar Jangkauan');
$status_bantuan  = trim($_POST['status_bantuan']  ?? 'Belum Disalurkan');
$fasilitas_publik_id = trim($_POST['fasilitas_publik_id'] ?? '');

if (!$nama || !$latitude || !$longitude) {
    echo json_encode(['status'=>'error','message'=>'Nama dan lokasi wajib diisi.']);
    exit;
}

$valid_status = ['Dalam Jangkauan','Luar Jangkauan'];
if (!in_array($status_jangkauan, $valid_status)) $status_jangkauan = 'Luar Jangkauan';

$fp_id = ($fasilitas_publik_id !== '') ? (int)$fasilitas_publik_id : null;

// Fungsi upload foto
function uploadFoto($file_input_name) {
    if (isset($_FILES[$file_input_name]) && $_FILES[$file_input_name]['error'] === UPLOAD_ERR_OK) {
        $file_tmp_path = $_FILES[$file_input_name]['tmp_name'];
        $file_name = $_FILES[$file_input_name]['name'];
        $file_size = $_FILES[$file_input_name]['size'];
        $file_type = mime_content_type($file_tmp_path);
        
        $allowed_mime_types = ['image/jpeg', 'image/png', 'image/jpg'];
        $max_size = 2 * 1024 * 1024; // 2MB
        
        if (in_array($file_type, $allowed_mime_types) && $file_size <= $max_size) {
            $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
            $new_file_name = uniqid($file_input_name . '_', true) . '.' . $file_extension;
            $upload_file_dir = '../uploads/';
            if (!is_dir($upload_file_dir)) {
                @mkdir($upload_file_dir, 0777, true);
            }
            $dest_path = $upload_file_dir . $new_file_name;
            
            if (@move_uploaded_file($file_tmp_path, $dest_path)) {
                return $new_file_name;
            }
        }
    }
    return null;
}

$foto_rumah = uploadFoto('foto_rumah');
$foto_kk = uploadFoto('foto_kk');

try {
    $stmt = $pdo->prepare(
        "INSERT INTO penduduk_miskin (nama, nik, keterangan, alamat, latitude, longitude, status_jangkauan, fasilitas_publik_id, foto_rumah, foto_kk, status_bantuan)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
    );
    $stmt->execute([$nama, $nik, $keterangan, $alamat, $latitude, $longitude, $status_jangkauan, $fp_id, $foto_rumah, $foto_kk, $status_bantuan]);
    $id   = $pdo->lastInsertId();
    
    $stmtSelect = $pdo->prepare("SELECT pm.*, fp.nama AS fp_nama FROM penduduk_miskin pm LEFT JOIN fasilitas_publik fp ON pm.fasilitas_publik_id = fp.id WHERE pm.id = ?");
    $stmtSelect->execute([$id]);
    $data = $stmtSelect->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode(['status'=>'success','data'=>$data]);
} catch (PDOException $e) {
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>
