<?php
// ketua/profil/index.php
$pageTitle = 'Profil Saya';
require_once '../../includes/config.php';
require_once '../../includes/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Mulai session jika belum dimulai
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Cek apakah user sudah login dan role-nya ketua
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'ketua') {
    // Redirect ke halaman login jika belum login atau bukan ketua
    setFlash('login_required', 'Anda harus login sebagai ketua yayasan untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Ambil data user
$db->query("SELECT * FROM users WHERE id = :id");
$db->bind(':id', $_SESSION['user_id']);
$user = $db->single();

if (!$user) {
    setFlash('profil', 'Data pengguna tidak ditemukan', 'danger');
    header('Location: ' . SITE_URL . '/ketua/dashboard.php');
    exit;
}

// Proses update profil
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_profile'])) {
    $nama_lengkap = sanitize($_POST['nama_lengkap'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $no_telp = sanitize($_POST['no_telp'] ?? '');
    $alamat = sanitize($_POST['alamat'] ?? '');
    
    // Validasi data
    $errors = [];
    
    if (empty($nama_lengkap)) {
        $errors[] = 'Nama lengkap harus diisi';
    }
    
    if (empty($email)) {
        $errors[] = 'Email harus diisi';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Format email tidak valid';
    } else {
        // Cek apakah email sudah digunakan oleh user lain
        $db->query("SELECT * FROM users WHERE email = :email AND id != :id");
        $db->bind(':email', $email);
        $db->bind(':id', $_SESSION['user_id']);
        if ($db->single()) {
            $errors[] = 'Email sudah digunakan oleh pengguna lain';
        }
    }
    
    // Jika tidak ada error, update profil
    if (empty($errors)) {
        $db->query("UPDATE users SET nama_lengkap = :nama_lengkap, email = :email, no_telp = :no_telp, alamat = :alamat, updated_at = NOW() WHERE id = :id");
        $db->bind(':nama_lengkap', $nama_lengkap);
        $db->bind(':email', $email);
        $db->bind(':no_telp', $no_telp);
        $db->bind(':alamat', $alamat);
        $db->bind(':id', $_SESSION['user_id']);
        
        if ($db->execute()) {
            // Update session
            $_SESSION['nama_lengkap'] = $nama_lengkap;
            $_SESSION['email'] = $email;
            
            // Log aktivitas
            logActivity('Update profil', 'user', $_SESSION['user_id'], 'Ketua mengupdate profilnya');
            
            setFlash('profil', 'Profil berhasil diperbarui', 'success');
            header('Location: ' . SITE_URL . '/ketua/profil/index.php');
            exit;
        } else {
            setFlash('profil', 'Gagal memperbarui profil', 'danger');
        }
    } else {
        // Gabungkan semua error
        $error_message = implode('<br>', $errors);
        setFlash('profil', $error_message, 'danger');
    }
}

// Proses ganti password
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // Validasi data
    $errors = [];
    
    if (empty($current_password)) {
        $errors[] = 'Password saat ini harus diisi';
    } else {
        // Verifikasi password saat ini
        if (!password_verify($current_password, $user->password)) {
            $errors[] = 'Password saat ini salah';
        }
    }
    
    if (empty($new_password)) {
        $errors[] = 'Password baru harus diisi';
    } elseif (strlen($new_password) < 6) {
        $errors[] = 'Password baru minimal 6 karakter';
    }
    
    if ($new_password !== $confirm_password) {
        $errors[] = 'Konfirmasi password tidak sesuai dengan password baru';
    }
    
    // Jika tidak ada error, update password
    if (empty($errors)) {
        // Hash password baru
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        
        // Update password
        $db->query("UPDATE users SET password = :password, updated_at = NOW() WHERE id = :id");
        $db->bind(':password', $hashed_password);
        $db->bind(':id', $_SESSION['user_id']);
        
        if ($db->execute()) {
            // Log aktivitas
            logActivity('Ganti password', 'user', $_SESSION['user_id'], 'Ketua mengganti passwordnya');
            
            setFlash('profil', 'Password berhasil diubah', 'success');
            header('Location: ' . SITE_URL . '/ketua/profil/index.php');
            exit;
        } else {
            setFlash('profil', 'Gagal mengubah password', 'danger');
        }
    } else {
        // Gabungkan semua error
        $error_message = implode('<br>', $errors);
        setFlash('profil', $error_message, 'danger');
    }
}

// Include header
require_once '../../includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/dashboard.php">
                            <i class="fas fa-tachometer-alt me-2"></i>
                            Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/kampanye/index.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Persetujuan Kampanye
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/laporan/index.php">
                            <i class="fas fa-chart-line me-2"></i>
                            Laporan Keuangan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/kegiatan/index.php">
                            <i class="fas fa-newspaper me-2"></i>
                            Kegiatan Yayasan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/staff/index.php">
                            <i class="fas fa-users-cog me-2"></i>
                            Manajemen Staff
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/ketua/profil/index.php">
                            <i class="fas fa-user-circle me-2"></i>
                            Profil Saya
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/auth/logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i>
                            Logout
                        </a>
                    </li>
                </ul>
                
                <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
                    <span>Pintasan</span>
                </h6>
                <ul class="nav flex-column mb-2">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>" target="_blank">
                            <i class="fas fa-external-link-alt me-2"></i>
                            Lihat Website
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- Content Area -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Profil Saya</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/ketua/dashboard.php" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Kembali ke Dashboard
                    </a>
                </div>
            </div>

            <?php flash(); ?>

            <div class="row">
                <!-- Informasi Profil -->
                <div class="col-md-6 mb-4">
                    <div class="card">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Informasi Profil</h5>
                        </div>
                        <div class="card-body">
                            <form action="" method="post">
                                <div class="mb-3">
                                    <label for="username" class="form-label">Username</label>
                                    <input type="text" class="form-control" id="username" value="<?= $user->username ?>" readonly disabled>
                                    <div class="form-text">Username tidak dapat diubah.</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="role" class="form-label">Role</label>
                                    <input type="text" class="form-control" id="role" value="<?= getRoleName($user->role) ?>" readonly disabled>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="nama_lengkap" class="form-label">Nama Lengkap <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="nama_lengkap" name="nama_lengkap" value="<?= $user->nama_lengkap ?>" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="email" class="form-label">Email <span class="text-danger">*</span></label>
                                    <input type="email" class="form-control" id="email" name="email" value="<?= $user->email ?>" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="no_telp" class="form-label">No. Telepon</label>
                                    <input type="text" class="form-control" id="no_telp" name="no_telp" value="<?= $user->no_telp ?? '' ?>">
                                </div>
                                
                                <div class="mb-3">
                                    <label for="alamat" class="form-label">Alamat</label>
                                    <textarea class="form-control" id="alamat" name="alamat" rows="3"><?= $user->alamat ?? '' ?></textarea>
                                </div>
                                
                                <div class="d-grid gap-2">
                                    <button type="submit" name="update_profile" class="btn btn-primary">
                                        <i class="fas fa-save me-1"></i> Simpan Perubahan
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                
                <!-- Ganti Password dan Informasi Akun -->
                <div class="col-md-6">
                    <!-- Ganti Password -->
                    <div class="card mb-4">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Ganti Password</h5>
                        </div>
                        <div class="card-body">
                            <form action="" method="post">
                                <div class="mb-3">
                                    <label for="current_password" class="form-label">Password Saat Ini <span class="text-danger">*</span></label>
                                    <input type="password" class="form-control" id="current_password" name="current_password" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="new_password" class="form-label">Password Baru <span class="text-danger">*</span></label>
                                    <input type="password" class="form-control" id="new_password" name="new_password" required>
                                    <div class="form-text">Password minimal 6 karakter.</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="confirm_password" class="form-label">Konfirmasi Password Baru <span class="text-danger">*</span></label>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                </div>
                                
                                <div class="d-grid gap-2">
                                    <button type="submit" name="change_password" class="btn btn-warning">
                                        <i class="fas fa-key me-1"></i> Ganti Password
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Informasi Akun -->
                    <div class="card">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Informasi Akun</h5>
                        </div>
                        <div class="card-body">
                            <table class="table table-borderless">
                                <tr>
                                    <th width="150">Status Akun</th>
                                    <td><span class="badge bg-success">Aktif</span></td>
                                </tr>
                                <tr>
                                    <th>Tanggal Dibuat</th>
                                    <td><?= date('d/m/Y H:i', strtotime($user->created_at)) ?></td>
                                </tr>
                                <tr>
                                    <th>Login Terakhir</th>
                                    <td>
                                        <?php
                                        // Ambil waktu login terakhir
                                        $db->query("SELECT created_at FROM logs WHERE user_id = :user_id AND activity = 'Login' ORDER BY created_at DESC LIMIT 1");
                                        $db->bind(':user_id', $_SESSION['user_id']);
                                        $last_login = $db->single();
                                        
                                        echo $last_login ? date('d/m/Y H:i', strtotime($last_login->created_at)) : 'Belum ada';
                                        ?>
                                    </td>
                                </tr>
                            </table>
                            
                            <div class="alert alert-info mt-3 mb-0">
                                <i class="fas fa-info-circle me-2"></i> Jika Anda mengalami masalah dengan akun Anda, silahkan hubungi administrator.
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
// Validasi form ganti password
document.addEventListener('DOMContentLoaded', function() {
    const passwordForm = document.querySelector('form[name="change_password"]');
    
    if (passwordForm) {
        passwordForm.addEventListener('submit', function(event) {
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            if (newPassword !== confirmPassword) {
                event.preventDefault();
                alert('Konfirmasi password tidak sesuai dengan password baru.');
            }
        });
    }
});
</script>

<?php require_once '../../includes/footer.php'; ?>