<?php
// bendahara/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 bendahara
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'bendahara') {
    // Redirect ke halaman login jika belum login atau bukan bendahara
    setFlash('login_required', 'Anda harus login sebagai bendahara untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

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

// Proses update profil jika form disubmit
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 email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        setFlash('error', 'Format email tidak valid', 'danger');
    } else {
        // Cek apakah email sudah digunakan oleh user lain
        $db->query("SELECT id FROM users WHERE email = :email AND id != :id");
        $db->bind(':email', $email);
        $db->bind(':id', $_SESSION['user_id']);
        $email_check = $db->single();
        
        if ($email_check) {
            setFlash('error', 'Email sudah digunakan oleh pengguna lain', 'danger');
        } else {
            // Update data profil
            $db->query("UPDATE users SET nama_lengkap = :nama_lengkap, email = :email, no_telp = :no_telp, alamat = :alamat 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;
                
                setFlash('profile', 'Profil berhasil diperbarui', 'success');
                
                // Log aktivitas
                logActivity('Update profil', 'user', $_SESSION['user_id'], 'Bendahara memperbarui profil');
                
                // Refresh untuk mendapatkan data terbaru
                header('Location: ' . SITE_URL . '/bendahara/profil/index.php');
                exit;
            } else {
                setFlash('error', 'Gagal memperbarui profil', 'danger');
            }
        }
    }
}

// Proses update password jika form disubmit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Validasi password
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        setFlash('password_error', 'Semua field password harus diisi', 'danger');
    } elseif ($new_password !== $confirm_password) {
        setFlash('password_error', 'Password baru dan konfirmasi password tidak cocok', 'danger');
    } elseif (strlen($new_password) < 6) {
        setFlash('password_error', 'Password baru minimal 6 karakter', 'danger');
    } else {
        // Verifikasi password lama
        if (!password_verify($current_password, $user->password)) {
            setFlash('password_error', 'Password lama tidak sesuai', 'danger');
        } else {
            // Update password
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $db->query("UPDATE users SET password = :password WHERE id = :id");
            $db->bind(':password', $hashed_password);
            $db->bind(':id', $_SESSION['user_id']);
            
            if ($db->execute()) {
                setFlash('password_success', 'Password berhasil diperbarui', 'success');
                
                // Log aktivitas
                logActivity('Update password', 'user', $_SESSION['user_id'], 'Bendahara memperbarui password');
            } else {
                setFlash('password_error', 'Gagal memperbarui password', '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 ?>/bendahara/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 ?>/bendahara/donasi/index.php">
                            <i class="fas fa-donate me-2"></i>
                            Verifikasi Donasi
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/bendahara/laporan/index.php">
                            <i class="fas fa-chart-bar me-2"></i>
                            Laporan Keuangan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/bendahara/kampanye/index.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Data Kampanye
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/bendahara/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>
            
            <div class="row">
                <div class="col-lg-4 col-xl-3">
                    <div class="card mb-4">
                        <div class="card-body text-center">
                            <img src="<?= SITE_URL ?>/assets/uploads/profile/<?= $user->foto_profil ?? 'default.jpg' ?>" alt="<?= $user->nama_lengkap ?>" class="rounded-circle img-fluid" style="width: 150px;">
                            <h5 class="my-3"><?= $user->nama_lengkap ?></h5>
                            <p class="text-muted mb-1"><?= getRoleName($user->role) ?></p>
                            <p class="text-muted mb-4"><?= $user->alamat ?? 'Belum diatur' ?></p>
                        </div>
                    </div>
                    
                    <div class="card mb-4">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-sm-4">
                                    <p class="mb-0 fw-bold">Username</p>
                                </div>
                                <div class="col-sm-8">
                                    <p class="text-muted mb-0"><?= $user->username ?></p>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-sm-4">
                                    <p class="mb-0 fw-bold">Email</p>
                                </div>
                                <div class="col-sm-8">
                                    <p class="text-muted mb-0"><?= $user->email ?></p>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-sm-4">
                                    <p class="mb-0 fw-bold">Telepon</p>
                                </div>
                                <div class="col-sm-8">
                                    <p class="text-muted mb-0"><?= $user->no_telp ?? 'Belum diatur' ?></p>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-sm-4">
                                    <p class="mb-0 fw-bold">Terdaftar</p>
                                </div>
                                <div class="col-sm-8">
                                    <p class="text-muted mb-0"><?= date('d/m/Y', strtotime($user->created_at)) ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-lg-8 col-xl-9">
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">Edit Profil</h5>
                        </div>
                        <div class="card-body">
                            <?php if (isset($_SESSION['profile'])): ?>
                                <div class="alert alert-success">
                                    <?= $_SESSION['profile'] ?>
                                    <?php unset($_SESSION['profile']); ?>
                                </div>
                            <?php endif; ?>
                            
                            <?php if (isset($_SESSION['error'])): ?>
                                <div class="alert alert-danger">
                                    <?= $_SESSION['error'] ?>
                                    <?php unset($_SESSION['error']); ?>
                                </div>
                            <?php endif; ?>
                            
                            <form action="" method="post">
                                <div class="mb-3">
                                    <label for="nama_lengkap" class="form-label">Nama Lengkap</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</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">Nomor 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>
                                
                                <button type="submit" name="update_profile" class="btn btn-primary">Simpan Perubahan</button>
                            </form>
                        </div>
                    </div>
                    
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">Ubah Password</h5>
                        </div>
                        <div class="card-body">
                            <?php if (isset($_SESSION['password_success'])): ?>
                                <div class="alert alert-success">
                                    <?= $_SESSION['password_success'] ?>
                                    <?php unset($_SESSION['password_success']); ?>
                                </div>
                            <?php endif; ?>
                            
                            <?php if (isset($_SESSION['password_error'])): ?>
                                <div class="alert alert-danger">
                                    <?= $_SESSION['password_error'] ?>
                                    <?php unset($_SESSION['password_error']); ?>
                                </div>
                            <?php endif; ?>
                            
                            <form action="" method="post">
                                <div class="mb-3">
                                    <label for="current_password" class="form-label">Password Saat Ini</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</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</label>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                </div>
                                
                                <button type="submit" name="update_password" class="btn btn-primary">Ubah Password</button>
                            </form>
                        </div>
                    </div>
                    
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">Aktivitas Terbaru</h5>
                        </div>
                        <div class="card-body">
                            <?php
                            // Ambil log aktivitas user
                            $db->query("SELECT * FROM logs WHERE user_id = :user_id ORDER BY created_at DESC LIMIT 5");
                            $db->bind(':user_id', $_SESSION['user_id']);
                            $logs = $db->resultSet();
                            
                            if (!empty($logs)):
                            ?>
                                <ul class="list-group">
                                    <?php foreach ($logs as $log): ?>
                                        <li class="list-group-item">
                                            <div class="d-flex justify-content-between">
                                                <span><?= $log->activity ?></span>
                                                <small><?= date('d/m/Y H:i', strtotime($log->created_at)) ?></small>
                                            </div>
                                            <?php if ($log->description): ?>
                                                <small class="text-muted"><?= $log->description ?></small>
                                            <?php endif; ?>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php else: ?>
                                <p class="text-center">Belum ada aktivitas tercatat.</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

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