<?php
session_start();
header('Content-Type: application/json');
include '../config/database.php';
$db = new Database();
$conn = $db->getConnection();

$id = $_POST['id'];
$foto = $_POST['foto_lama']?? 'default.png';

// Upload foto
if(!empty($_FILES['foto']['name'])){
    $ext = pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION);
    $foto = 'user_'.time().'.'.$ext;
    move_uploaded_file($_FILES['foto']['tmp_name'], '../assets/img/user/'.$foto);
}

// Cek username duplikat
$stmt = $conn->prepare("SELECT id FROM users WHERE username=? AND id!=?");
$stmt->execute([$_POST['username'], $id]);
if($stmt->fetch()){
    die(json_encode(['status'=>'error','message'=>'Username sudah dipakai']));
}

$data = [
    'nama'=>$_POST['nama'],
    'username'=>$_POST['username'],
    'role'=>$_POST['role'],
    'gereja_id'=>$_POST['gereja_id']?:NULL,
    'no_hp'=>$_POST['no_hp'],
    'foto'=>$foto,
    'status'=>'Aktif'
];

// Kalau password diisi, hash baru
if(!empty($_POST['password'])){
    $data['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
}

if(empty($id)){
    // INSERT
    if(empty($_POST['password'])) die(json_encode(['status'=>'error','message'=>'Password wajib diisi untuk user baru']));
    $sql = "INSERT INTO users (".implode(',',array_keys($data)).") VALUES (:".implode(',:',array_keys($data)).")";
} else {
    // UPDATE
    $sql = "UPDATE users SET ";
    foreach($data as $k=>$v){ $sql.= "$k=:$k,"; }
    $sql = rtrim($sql,',')." WHERE id=:id";
    $data['id'] = $id;
}

$stmt = $conn->prepare($sql);
$stmt->execute($data);
echo json_encode(['status'=>'success','message'=>'Data pengurus disimpan']);
?>