<?php
session_start();
include '../config/database.php';
$db = new Database();
$conn = $db->getConnection();

$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'];
$gereja_id = $_SESSION['gereja_id'];

if($role != 'gembala'){
    die('<div class="alert alert-danger">Akses ditolak!</div>');
}

if(!$gereja_id){
    die('<div class="alert alert-danger">Akun gembala belum terhubung ke gereja.</div>');
}

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

// TAMBAH BENDAHARA DARI JEMAAT GEREJA INI
if($aksi == 'tambah'){
    $jemaat_id = $_POST['jemaat_id'];
    $username = $_POST['username'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    
    // PASTIKAN JEMAAT DARI GEREJA INI + AMBIL FOTO
    $j = $conn->prepare("SELECT nama_lengkap, foto FROM jemaat WHERE id=? AND gereja_id=?");
    $j->execute([$jemaat_id, $gereja_id]);
    $jemaat = $j->fetch(PDO::FETCH_ASSOC);
    
    if(!$jemaat){
        echo json_encode(['status'=>'error','message'=>'Jemaat tidak ditemukan di gereja Anda!']);
        exit;
    }
    
    $nama = $jemaat['nama_lengkap'];
    $foto = $jemaat['foto'] ?: 'default.png';
    
    $cek = $conn->prepare("SELECT id FROM users WHERE username=?");
    $cek->execute([$username]);
    if($cek->rowCount() > 0){
        echo json_encode(['status'=>'error','message'=>'Username sudah digunakan!']);
        exit;
    }
    
    // INSERT + gereja_id + foto
    $sql = "INSERT INTO users (nama, username, password, role, gereja_id, foto) VALUES (?,?,?,'bendahara',?,?)";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$nama, $username, $password, $gereja_id, $foto]);
    
    $user_baru = $conn->lastInsertId();
    
    $sql2 = "INSERT INTO user_akses (user_id, menu, gereja_id, dibuat_oleh) VALUES (?,?,?,?)";
    $conn->prepare($sql2)->execute([$user_baru, 'keuangan', $gereja_id, $user_id]);
    
    echo json_encode(['status'=>'sukses']);
    exit;
}

// HAPUS
if($aksi == 'hapus'){
    $id = $_POST['id'];
    $conn->prepare("DELETE FROM users WHERE id=? AND role='bendahara' AND gereja_id=?")->execute([$id, $gereja_id]);
    $conn->prepare("DELETE FROM user_akses WHERE user_id=? AND gereja_id=?")->execute([$id, $gereja_id]);
    echo json_encode(['status'=>'sukses']);
    exit;
}

// LIST JEMAAT GEREJA INI SAJA
$list_jemaat = $conn->prepare("SELECT id, nama_lengkap, no_anggota FROM jemaat WHERE gereja_id=? ORDER BY nama_lengkap");
$list_jemaat->execute([$gereja_id]);

// LIST BENDAHARA - FIX: AMBIL u.foto SECARA EKSPLISIT
$list = $conn->prepare("SELECT u.id, u.nama, u.username, u.foto, a.created_at as tgl_akses 
                        FROM users u 
                        JOIN user_akses a ON u.id = a.user_id 
                        WHERE a.gereja_id=? AND u.role='bendahara'");
$list->execute([$gereja_id]);
?>

<div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Kelola Bendahara</h1>
    <span class="badge badge-info"><?= $_SESSION['nama_gereja']?></span>
</div>

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">Tambah Akun Bendahara</h6>
    </div>
    <div class="card-body">
        <form id="formBendahara">
            <input type="hidden" name="aksi" value="tambah">
            <div class="form-row">
                <div class="form-group col-md-4">
                    <label>Pilih Jemaat *</label>
                    <select name="jemaat_id" class="form-control select2" required>
                        <option value="">- Pilih Jemaat -</option>
                        <?php while($j = $list_jemaat->fetch(PDO::FETCH_ASSOC)):?>
                        <option value="<?= $j['id']?>"><?= $j['nama_lengkap']?> - <?= $j['no_anggota']?></option>
                        <?php endwhile;?>
                    </select>
                    <small class="text-muted">Foto akan otomatis diambil dari data jemaat</small>
                </div>
                <div class="form-group col-md-3">
                    <label>Username *</label>
                    <input type="text" name="username" class="form-control" required>
                </div>
                <div class="form-group col-md-3">
                    <label>Password *</label>
                    <input type="text" name="password" class="form-control" value="bendahara123" required>
                </div>
                <div class="form-group col-md-2">
                    <label>&nbsp;</label>
                    <button type="submit" class="btn btn-primary btn-block">
                        <i class="fa fa-plus"></i> Buat Akun
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">Daftar Bendahara</h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Foto</th>
                        <th>Nama Bendahara</th>
                        <th>Username</th>
                        <th>Tgl Dibuat</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $no=1; while($row = $list->fetch(PDO::FETCH_ASSOC)):?>
                    <tr>
                        <td><?= $no++?></td>
                        <td class="text-center">
                            <img src="assets/img/jemaat/<?= !empty($row['foto']) ? $row['foto'] : 'default.png' ?>"  
                                 onerror="this.onerror=null;this.src='../assets/img/jemaat/default.png';"
                                 width="40" height="40" 
                                 class="rounded-circle" 
                                 style="object-fit:cover; border: 1px solid #ddd;">
                        </td>
                        <td><?= $row['nama']?></td>
                        <td><?= $row['username']?></td>
                        <td><?= date('d/m/Y', strtotime($row['tgl_akses']))?></td>
                        <td>
                            <button class="btn btn-danger btn-sm" onclick="hapusBendahara(<?= $row['id']?>)">
                                <i class="fa fa-trash"></i> Hapus
                            </button>
                        </td>
                    </tr>
                    <?php endwhile;?>
                    <?php if($no==1):?>
                    <tr><td colspan="6" class="text-center">Belum ada bendahara</td></tr>
                    <?php endif;?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('.select2').select2({placeholder: "Ketik nama jemaat..."});
});

$('#formBendahara').submit(function(e){
    e.preventDefault();
    $.post('pages/kelola_bendahara.php', $(this).serialize(), function(res){
        let d = JSON.parse(res);
        if(d.status == 'sukses'){
            Swal.fire('Berhasil!','Akun bendahara dibuat','success');
            loadPage('kelola_bendahara');
        } else {
            Swal.fire('Gagal!', d.message, 'error');
        }
    });
});

function hapusBendahara(id){
    Swal.fire({
        title: 'Hapus Bendahara?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Ya, Hapus!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.post('pages/kelola_bendahara.php', {aksi:'hapus',id:id}, function(){
                Swal.fire('Terhapus!','Bendahara dihapus','success');
                loadPage('kelola_bendahara');
            });
        }
    });
}
</script>