<?php
require_once '../config/auth.php';
cek_role('admin_dpw');
require_once '../config/database.php';
header('Content-Type: application/json');

$db = new Database();
$conn = $db->getConnection();

$action = $_POST['action']?? '';

try {
    if ($action == 'tambah_gembala') {
        $nama = $_POST['nama'];
        $username = $_POST['username'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $no_hp = $_POST['no_hp'];
        $status = $_POST['status'];
        $nama_gereja = $_POST['nama_gereja'];
        $alamat_gereja = $_POST['alamat_gereja'];
        
        // Cek username duplikat
        $cek = $conn->prepare("SELECT id FROM users WHERE username =?");
        $cek->execute([$username]);
        if ($cek->rowCount() > 0) {
            throw new Exception('Username sudah digunakan');
        }

        // Cek nama gereja duplikat
        $cek_gereja = $conn->prepare("SELECT id FROM gereja WHERE nama_gereja =?");
        $cek_gereja->execute([$nama_gereja]);
        if ($cek_gereja->rowCount() > 0) {
            throw new Exception('Nama gereja sudah ada. Gunakan nama unik + inisial gembala');
        }

        $conn->beginTransaction();

        // 1. INSERT gereja dulu
        $stmt1 = $conn->prepare("INSERT INTO gereja (nama_gereja, alamat, sinode) VALUES (?,?, 'GBI')");
        $stmt1->execute([$nama_gereja, $alamat_gereja]);
        $gereja_id = $conn->lastInsertId();

        // 2. Upload foto jika ada
        $foto = 'default.png';
        if (!empty($_FILES['foto']['name'])) {
            $ext = pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION);
            $foto = 'gembala_'. time(). '.'. $ext;
            move_uploaded_file($_FILES['foto']['tmp_name'], '../assets/img/users/'. $foto);
        }

        // 3. INSERT gembala
        $stmt2 = $conn->prepare("INSERT INTO users (nama, username, password, role, gereja_id, no_hp, foto, status) VALUES (?,?,?, 'gembala',?,?,?,?)");
        $stmt2->execute([$nama, $username, $password, $gereja_id, $no_hp, $foto, $status]);

        $conn->commit();
        echo json_encode(['status' => 'sukses', 'message' => 'Gembala + Gereja baru berhasil ditambah']);

    } elseif ($action == 'edit_gembala') {
        $id = $_POST['id'];
        $gereja_id = $_POST['gereja_id'];
        $nama = $_POST['nama'];
        $username = $_POST['username'];
        $no_hp = $_POST['no_hp'];
        $status = $_POST['status'];
        $nama_gereja = $_POST['nama_gereja'];
        $alamat_gereja = $_POST['alamat_gereja'];

        // Cek username duplikat kecuali diri sendiri
        $cek = $conn->prepare("SELECT id FROM users WHERE username =? AND id!=?");
        $cek->execute([$username, $id]);
        if ($cek->rowCount() > 0) {
            throw new Exception('Username sudah digunakan');
        }

        $conn->beginTransaction();

        // 1. Update gereja
        $stmt1 = $conn->prepare("UPDATE gereja SET nama_gereja=?, alamat=? WHERE id=?");
        $stmt1->execute([$nama_gereja, $alamat_gereja, $gereja_id]);

        // 2. Update user gembala
        $sql = "UPDATE users SET nama=?, username=?, no_hp=?, status=?";
        $params = [$nama, $username, $no_hp, $status];

        if (!empty($_POST['password'])) {
            $sql.= ", password=?";
            $params[] = password_hash($_POST['password'], PASSWORD_DEFAULT);
        }

        if (!empty($_FILES['foto']['name'])) {
            $ext = pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION);
            $foto = 'gembala_'. time(). '.'. $ext;
            move_uploaded_file($_FILES['foto']['tmp_name'], '../assets/img/users/'. $foto);
            $sql.= ", foto=?";
            $params[] = $foto;
        }

        $sql.= " WHERE id=?";
        $params[] = $id;
        $stmt2 = $conn->prepare($sql);
        $stmt2->execute($params);

        $conn->commit();
        echo json_encode(['status' => 'sukses', 'message' => 'Data gembala & gereja berhasil diupdate']);

    } elseif ($action == 'hapus_gembala') {
        $id = $_POST['id'];
        $gereja_id = $_POST['gereja_id'];

        $conn->beginTransaction();
        // Hapus gembala
        $stmt1 = $conn->prepare("DELETE FROM users WHERE id =? AND role = 'gembala'");
        $stmt1->execute([$id]);
        
        // Hapus gerejanya juga biar nggak jadi yatim
        $stmt2 = $conn->prepare("DELETE FROM gereja WHERE id =?");
        $stmt2->execute([$gereja_id]);
        
        $conn->commit();
        echo json_encode(['status' => 'sukses', 'message' => 'Gembala dan gereja berhasil dihapus']);
    }
} catch (Exception $e) {
    if ($conn->inTransaction()) $conn->rollBack();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>