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

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

$response = ['status' => 'error', 'message' => 'Aksi tidak dikenal'];
$action = $_POST['action']?? '';

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']?? 'Aktif';
    $gereja_id = $_POST['gereja_id']?? ''; // TAMBAHAN
    
    // VALIDASI GEREJA WAJIB
    if(empty($gereja_id)){
        echo json_encode(['status' => 'error', 'message' => 'Gereja wajib dipilih']);
        exit;
    }
    
    $cek = $conn->prepare("SELECT id FROM users WHERE username =?");
    $cek->execute([$username]);
    if($cek->rowCount() > 0){
        echo json_encode(['status' => 'error', 'message' => 'Username sudah dipakai']);
        exit;
    }
    
    $foto = 'default.png';
    if(isset($_FILES['foto']) && $_FILES['foto']['name']!= ''){
        $ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
        if(in_array($ext, ['jpg','jpeg','png'])){
            $foto = 'gembala_'.time().'.'.$ext;
            move_uploaded_file($_FILES['foto']['tmp_name'], '../assets/img/users/'.$foto);
        }
    }
    
    $conn->beginTransaction();
    try {
        // 1. INSERT USER GEMBALA
        $sql = "INSERT INTO users (nama, username, password, no_hp, foto, role, status) VALUES (?,?,?,?,?,'gembala',?)";
        $stmt = $conn->prepare($sql);
        $stmt->execute([$nama, $username, $password, $no_hp, $foto, $status]);
        $user_id = $conn->lastInsertId();

        // 2. UPDATE/INSERT GEREJA - KUNCINYA DI SINI
        if($gereja_id == 'new'){
            // BUAT GEREJA BARU
            if(empty($_POST['nama_gereja_baru'])){
                throw new Exception('Nama gereja baru wajib diisi');
            }
            $sql_g = "INSERT INTO gereja (nama_gereja, distrik, alamat, gembala_id, status) VALUES (?,?,?,?,'Aktif')";
            $stmt_g = $conn->prepare($sql_g);
            $stmt_g->execute([$_POST['nama_gereja_baru'], $_POST['distrik_baru']??'', $_POST['alamat_gereja_baru']??'', $user_id]);
        } else {
            // LEPAS GEMBALA LAMA DARI GEREJA INI KALO ADA
            $conn->prepare("UPDATE gereja SET gembala_id=NULL WHERE id=?")->execute([$gereja_id]);
            // SET GEMBALA BARU KE GEREJA YANG DIPILIH
            $sql_g = "UPDATE gereja SET gembala_id=? WHERE id=?";
            $stmt_g = $conn->prepare($sql_g);
            $stmt_g->execute([$user_id, $gereja_id]);
        }

        $conn->commit();
        $response = ['status' => 'sukses'];
    } catch(Exception $e){
        $conn->rollback();
        $response = ['status' => 'error', 'message' => $e->getMessage()];
    }

} elseif($action == 'edit_gembala'){
    $id = $_POST['id'];
    $nama = $_POST['nama'];
    $username = $_POST['username'];
    $no_hp = $_POST['no_hp']?? '';
    $status = $_POST['status']?? 'Aktif';
    $gereja_id = $_POST['gereja_id']?? ''; // TAMBAHAN
    
    // VALIDASI GEREJA WAJIB
    if(empty($gereja_id)){
        echo json_encode(['status' => 'error', 'message' => 'Gereja wajib dipilih']);
        exit;
    }
    
    $cek = $conn->prepare("SELECT id FROM users WHERE username =? AND id!=?");
    $cek->execute([$username, $id]);
    if($cek->rowCount() > 0){
        echo json_encode(['status' => 'error', 'message' => 'Username sudah dipakai']);
        exit;
    }
    
    $old = $conn->prepare("SELECT foto FROM users WHERE id =?");
    $old->execute([$id]);
    $foto = $old->fetchColumn();
    
    if(isset($_FILES['foto']) && $_FILES['foto']['name']!= ''){
        $ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
        if(in_array($ext, ['jpg','jpeg','png'])){
            if($foto!= 'default.png' && file_exists('../assets/img/users/'.$foto)){
                unlink('../assets/img/users/'.$foto);
            }
            $foto = 'gembala_'.time().'.'.$ext;
            move_uploaded_file($_FILES['foto']['tmp_name'], '../assets/img/users/'.$foto);
        }
    }
    
    $conn->beginTransaction();
    try {
        // 1. UPDATE USER
        if(!empty($_POST['password'])){
            $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $sql = "UPDATE users SET nama=?, username=?, password=?, no_hp=?, foto=?, status=? WHERE id=?";
            $params = [$nama, $username, $password, $no_hp, $foto, $status, $id];
        } else {
            $sql = "UPDATE users SET nama=?, username=?, no_hp=?, foto=?, status=? WHERE id=?";
            $params = [$nama, $username, $no_hp, $foto, $status, $id];
        }
        $stmt = $conn->prepare($sql);
        $stmt->execute($params);

        // 2. UPDATE GEREJA - LEPAS DARI GEREJA LAMA DULU
        $conn->prepare("UPDATE gereja SET gembala_id=NULL WHERE gembala_id=?")->execute([$id]);
        
        if($gereja_id == 'new'){
            // BIKIN GEREJA BARU
            if(empty($_POST['nama_gereja_baru'])){
                throw new Exception('Nama gereja baru wajib diisi');
            }
            $sql_g = "INSERT INTO gereja (nama_gereja, distrik, alamat, gembala_id, status) VALUES (?,?,?,?,'Aktif')";
            $stmt_g = $conn->prepare($sql_g);
            $stmt_g->execute([$_POST['nama_gereja_baru'], $_POST['distrik_baru']??'', $_POST['alamat_gereja_baru']??'', $id]);
        } else {
            // SET KE GEREJA YANG DIPILIH
            $sql_g = "UPDATE gereja SET gembala_id=? WHERE id=?";
            $stmt_g = $conn->prepare($sql_g);
            $stmt_g->execute([$id, $gereja_id]);
        }

        $conn->commit();
        $response = ['status' => 'sukses'];
    } catch(Exception $e){
        $conn->rollback();
        $response = ['status' => 'error', 'message' => $e->getMessage()];
    }

} elseif($action == 'hapus_gembala'){
    $id = $_POST['id'];
    
    // SEBELUM HAPUS, LEPAS DULU DARI GEREJA
    $conn->prepare("UPDATE gereja SET gembala_id=NULL WHERE gembala_id=?")->execute([$id]);
    
    $old = $conn->prepare("SELECT foto FROM users WHERE id =?");
    $old->execute([$id]);
    $foto = $old->fetchColumn();
    if($foto!= 'default.png' && file_exists('../assets/img/users/'.$foto)){
        unlink('../assets/img/users/'.$foto);
    }
    
    $stmt = $conn->prepare("DELETE FROM users WHERE id =? AND role = 'gembala'");
    if($stmt->execute([$id])){
        $response = ['status' => 'sukses'];
    }
}

echo json_encode($response);
?>