<?php
require_once '../config/auth.php';
cek_role('gembala');

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

if(!$gereja_id){
    die('<div class="alert alert-danger">Error: gereja_id = 0. Cek tabel users untuk user_id = '.$user_id.'</div>');
}

// PATH ABSOLUTE DARI ROOT WEB
$base_url = '/simjedpw/'; // GANTI KALO FOLDER LU BEDA
$folder_gereja = '../assets/img/gereja/';
$url_gereja = $base_url.'assets/img/gereja/';

if (!file_exists($folder_gereja)) {
    mkdir($folder_gereja, 0777, true);
}

// HANDLE AJAX UPDATE
if(isset($_POST['aksi']) && $_POST['aksi'] == 'update'){
    header('Content-Type: application/json');
    $logo_db = $_POST['logo_lama'];

    if(isset($_FILES['logo']) && $_FILES['logo']['error'] == 0){
        $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','webp'];
        
        if(!in_array($ext, $allowed)){
            echo json_encode(['status'=>'gagal','pesan'=>'Format harus jpg/jpeg/png/webp']);
            exit;
        }
        
        if($_FILES['logo']['size'] > 2097152){
            echo json_encode(['status'=>'gagal','pesan'=>'Ukuran maksimal 2MB']);
            exit;
        }

        if($logo_db && file_exists($folder_gereja.$logo_db)){
            unlink($folder_gereja.$logo_db);
        }
        
        $logo_db = 'gereja_'.$gereja_id.'_'.time().'.'.$ext;
        if(!move_uploaded_file($_FILES['logo']['tmp_name'], $folder_gereja.$logo_db)){
            echo json_encode(['status'=>'gagal','pesan'=>'Gagal upload file']);
            exit;
        }
    }
    
    $sql = "UPDATE gereja SET nama_gereja=?, alamat=?, no_telepon=?, email=?, tanggal_berdiri=?, visi=?, misi=?, logo=? WHERE id=?";
    $conn->prepare($sql)->execute([$_POST['nama_gereja'], $_POST['alamat'], $_POST['no_telepon'], $_POST['email'], $_POST['tanggal_berdiri'], $_POST['visi'], $_POST['misi'], $logo_db, $gereja_id]);
    echo json_encode(['status'=>'sukses']);
    exit;
}

$stmt = $conn->prepare("SELECT * FROM gereja WHERE id =?");
$stmt->execute([$gereja_id]);
$g = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$g){
    die('<div class="alert alert-danger">Data gereja ID '.$gereja_id.' tidak ada di tabel gereja. Cek tabel gereja.</div>');
}

// CEK LOGO - PAKE URL ABSOLUTE
if(!empty($g['logo']) && file_exists($folder_gereja.$g['logo'])){
    $logo_tampil = $url_gereja.$g['logo'].'?v='.time();
} else {
    $logo_tampil = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNTAiIGhlaWdodD0iMTUwIiB2aWV3Qm94PSIwIDAgMTUwIDE1MCI+PGNpcmNsZSBjeD0iNzUiIGN5PSI3NSIgcj0iNzAiIGZpbGw9IiM0Zjc3ZGYiLz48dGV4dCB4PSI3NSIgeT0iODUiIGZvbnQtc2l6ZT0iNDAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmb250LWZhbWlseT0iQXJpYWwiPkdCSSA8L3RleHQ+PC9zdmc+';
}

// HAPUS DEBUG KALO UDAH JALAN
// echo '<div class="alert alert-info"><b>DEBUG:</b> Path Logo: '.$folder_gereja.$g['logo'].' | File Ada: '.(file_exists($folder_gereja.$g['logo'])?'YA':'TIDAK').' | Nama DB: '.$g['logo'].'</div>';
?>

<h1 class="h3 mb-4 text-gray-800">Profil Gereja</h1>

<div class="row">
    <div class="col-lg-4">
        <div class="card shadow mb-4">
            <div class="card-body text-center">
                <img src="<?= $logo_tampil?>" id="previewLogo" class="rounded-circle img-fluid mb-3" style="width:150px;height:150px;object-fit:cover;border:3px solid #4e73df;" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxNTAiIGhlaWdodD0iMTUwIiB2aWV3Qm94PSIwIDAgMTUwIDE1MCI+PGNpcmNsZSBjeD0iNzUiIGN5PSI3NSIgcj0iNzAiIGZpbGw9IiM0Zjc3ZGYiLz48dGV4dCB4PSI3NSIgeT0iODUiIGZvbnQtc2l6ZT0iNDAiIGZpbGw9IndoaXRlIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBmb250LWZhbWlseT0iQXJpYWwiPkdCSSA8L3RleHQ+PC9zdmc+'">
                <h4><?= htmlspecialchars($g['nama_gereja'])?></h4>
                <p class="text-muted"><?= htmlspecialchars($g['sinode']?: 'GBI')?></p>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">Detail Gereja</h6>
                <button class="btn btn-warning btn-sm" onclick="editProfil()"><i class="fa fa-edit"></i> Edit Profil</button>
            </div>
            <div class="card-body">
                <table class="table table-borderless">
                    <tr><th width="200">Alamat</th><td><?= htmlspecialchars($g['alamat']?:'-')?></td></tr>
                    <tr><th>No. Telepon</th><td><?= htmlspecialchars($g['no_telepon']?:'-')?></td></tr>
                    <tr><th>Email</th><td><?= htmlspecialchars($g['email']?:'-')?></td></tr>
                    <tr><th>Tanggal Berdiri</th><td><?= $g['tanggal_berdiri']?date('d F Y',strtotime($g['tanggal_berdiri'])):'-'?></td></tr>
                </table>
            </div>
        </div>

        <div class="card shadow mb-4">
            <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Visi Gereja</h6></div>
            <div class="card-body"><?= $g['visi']?nl2br(htmlspecialchars($g['visi'])):'<i class="text-muted">Belum diisi</i>'?></div>
        </div>

        <div class="card shadow mb-4">
            <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Misi Gereja</h6></div>
            <div class="card-body"><?= $g['misi']?nl2br(htmlspecialchars($g['misi'])):'<i class="text-muted">Belum diisi</i>'?></div>
        </div>
    </div>
</div>

<!-- MODAL EDIT -->
<div class="modal fade" id="modalProfil" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form id="formProfil" enctype="multipart/form-data">
                <div class="modal-header"><h5 class="modal-title">Edit Profil Gereja</h5><button type="button" class="close" data-dismiss="modal"><span>&times;</span></button></div>
                <div class="modal-body">
                    <input type="hidden" name="aksi" value="update">
                    <input type="hidden" name="logo_lama" value="<?= $g['logo']?>">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Nama Gereja</label>
                                <input type="text" name="nama_gereja" class="form-control" value="<?= htmlspecialchars($g['nama_gereja'])?>" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Logo Gereja</label>
                                <input type="file" name="logo" id="inputLogo" class="form-control" accept="image/*">
                                <small class="text-muted">Kosongkan jika tidak ganti logo. Max 2MB</small>
                                <div class="mt-2">
                                    <img src="<?= $logo_tampil?>" id="previewLogoModal" class="img-thumbnail" style="width:100px;height:100px;object-fit:cover;">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group"><label>Alamat</label><textarea name="alamat" class="form-control" rows="2"><?= htmlspecialchars($g['alamat'])?></textarea></div>
                    <div class="row">
                        <div class="col-md-4"><div class="form-group"><label>No. Telepon</label><input type="text" name="no_telepon" class="form-control" value="<?= htmlspecialchars($g['no_telepon'])?>"></div></div>
                        <div class="col-md-4"><div class="form-group"><label>Email</label><input type="email" name="email" class="form-control" value="<?= htmlspecialchars($g['email'])?>"></div></div>
                        <div class="col-md-4"><div class="form-group"><label>Tanggal Berdiri</label><input type="date" name="tanggal_berdiri" class="form-control" value="<?= $g['tanggal_berdiri']?>"></div></div>
                    </div>
                    <div class="form-group"><label>Visi Gereja</label><textarea name="visi" class="form-control" rows="3"><?= htmlspecialchars($g['visi'])?></textarea></div>
                    <div class="form-group"><label>Misi Gereja</label><textarea name="misi" class="form-control" rows="4"><?= htmlspecialchars($g['misi'])?></textarea></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary" id="btnSimpan">Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$('#inputLogo').change(function(){
    const file = this.files[0];
    if (file){
        if(file.size > 2097152){
            Swal.fire('Error','Ukuran file maksimal 2MB','error');
            $(this).val('');
            return false;
        }
        let reader = new FileReader();
        reader.onload = function(e){
            $('#previewLogoModal').attr('src', e.target.result);
        }
        reader.readAsDataURL(file);
    }
});

function editProfil(){$('#modalProfil').modal('show');}

$('#formProfil').submit(function(e){
    e.preventDefault();
    $('#btnSimpan').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Menyimpan...');
    $.ajax({
        url: 'pages/profil.php', type: 'POST', data: new FormData(this), contentType: false, processData: false, dataType: 'json',
        success: function(res){
            if(res.status=='sukses'){
                $('#modalProfil').modal('hide');
                Swal.fire('Berhasil!','Profil gereja berhasil diupdate','success').then(()=>{
                    location.reload();
                });
            } else {
                Swal.fire('Gagal!',res.pesan || 'Gagal update','error');
            }
        },
        error: function(xhr){
            console.log(xhr.responseText);
            Swal.fire('Error!','Terjadi kesalahan server','error');
        },
        complete: function(){$('#btnSimpan').prop('disabled', false).html('Simpan Perubahan');}
    });
});
</script>