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

// Koneksi database dan ambil data user
$db = dbConnect();
$id = $_SESSION['user_id'];

$db->query("SELECT * FROM users WHERE id = :id");
$db->bind(':id', $id);
$user = $db->single();

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

// Proses update profil jika form disubmit
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_profile') {
    $nama_lengkap = sanitize($_POST['nama_lengkap'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $no_telp = sanitize($_POST['no_telp'] ?? '');
    $alamat = sanitize($_POST['alamat'] ?? '');
    
    $errors = [];
    
    // Validasi data
    if (empty($nama_lengkap)) {
        $errors[] = 'Nama lengkap tidak boleh kosong';
    }
    
    if (empty($email)) {
        $errors[] = 'Email tidak boleh kosong';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Format email tidak valid';
    }
    
    // Cek apakah email sudah digunakan oleh user lain
    if ($email != $user->email) {
        $db->query("SELECT * FROM users WHERE email = :email AND id != :id");
        $db->bind(':email', $email);
        $db->bind(':id', $id);
        $check_email = $db->single();
        
        if ($check_email) {
            $errors[] = 'Email sudah digunakan oleh user lain';
        }
    }
    
    // Upload foto profil jika ada
    $foto_profil = $user->foto_profil; // Default ke foto yang sudah ada
    if (isset($_FILES['foto_profil']) && $_FILES['foto_profil']['error'] != UPLOAD_ERR_NO_FILE) {
        $upload_dir = UPLOAD_DIR . 'profile/';
        $upload_result = uploadFile($_FILES['foto_profil'], $upload_dir, 'gambar');
        
        if ($upload_result === false) {
            $errors[] = 'Upload foto profil gagal. Pastikan format file adalah JPG, JPEG, atau PNG dan ukuran tidak lebih dari 2MB';
        } else {
            // Hapus foto lama jika bukan default
            if ($foto_profil != 'default.jpg') {
                $old_image_path = UPLOAD_DIR . 'profile/' . $foto_profil;
                if (file_exists($old_image_path)) {
                    unlink($old_image_path);
                }
            }
            $foto_profil = $upload_result;
        }
    }
    
    // Jika tidak ada error, update data
    if (empty($errors)) {
        $db->query("UPDATE users SET 
                   nama_lengkap = :nama_lengkap, 
                   email = :email, 
                   no_telp = :no_telp, 
                   alamat = :alamat,
                   foto_profil = :foto_profil
                   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(':foto_profil', $foto_profil);
        $db->bind(':id', $id);
        
        if ($db->execute()) {
            // Update session data
            $_SESSION['nama_lengkap'] = $nama_lengkap;
            $_SESSION['email'] = $email;
            
            // Log aktivitas
            logActivity('Update profil', 'user', $id, 'Sekretaris mengupdate profil');
            
            setFlash('profil', 'Profil berhasil diupdate', 'success');
            header('Location: ' . SITE_URL . '/sekretaris/profil/index.php');
            exit;
        } else {
            setFlash('profil', 'Gagal update profil', 'danger');
        }
    } else {
        // Gabungkan semua error
        $error_message = implode('<br>', $errors);
        setFlash('profil', $error_message, 'danger');
    }
}

// Proses ganti password jika form disubmit
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'change_password') {
    $old_password = $_POST['old_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    $errors = [];
    
    // Validasi password lama
    if (empty($old_password)) {
        $errors[] = 'Password lama tidak boleh kosong';
    } elseif (!password_verify($old_password, $user->password)) {
        $errors[] = 'Password lama tidak sesuai';
    }
    
    // Validasi password baru
    if (empty($new_password)) {
        $errors[] = 'Password baru tidak boleh kosong';
    } elseif (strlen($new_password) < 6) {
        $errors[] = 'Password baru minimal 6 karakter';
    }
    
    // Validasi konfirmasi password
    if (empty($confirm_password)) {
        $errors[] = 'Konfirmasi password tidak boleh kosong';
    } elseif ($new_password != $confirm_password) {
        $errors[] = 'Konfirmasi password tidak sesuai';
    }
    
    // Jika tidak ada error, update password
    if (empty($errors)) {
        $password = password_hash($new_password, PASSWORD_DEFAULT);
        
        $db->query("UPDATE users SET password = :password WHERE id = :id");
        $db->bind(':password', $password);
        $db->bind(':id', $id);
        
        if ($db->execute()) {
            // Log aktivitas
            logActivity('Ganti password', 'user', $id, 'Sekretaris mengganti password');
            
            setFlash('profil', 'Password berhasil diubah', 'success');
            header('Location: ' . SITE_URL . '/sekretaris/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 -->
                <?php require_once '../../includes/sidebar-sekretaris.php'; ?>


        <!-- 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>

            <?php flash(); ?>

            <div class="row">
                <!-- Profil Info -->
                <div class="col-md-4 mb-4">
                    <div class="card">
                        <div class="card-body text-center">
                            <img src="<?= SITE_URL ?>/assets/uploads/profile/<?= $user->foto_profil ?? 'default.jpg' ?>" alt="Foto Profil" class="rounded-circle img-fluid profile-img mb-3" style="width: 150px; height: 150px; object-fit: cover;">
                            <h5 class="card-title"><?= $user->nama_lengkap ?></h5>
                            <p class="card-text text-muted"><?= getRoleName($user->role) ?></p>
                            <div class="d-grid gap-2">
                                <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#editProfileForm" aria-expanded="false">
                                    <i class="fas fa-edit me-1"></i> Edit Profil
                                </button>
                                <button class="btn btn-outline-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#changePasswordForm" aria-expanded="false">
                                    <i class="fas fa-key me-1"></i> Ganti Password
                                </button>
                            </div>
                        </div>
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item">
                                <i class="fas fa-envelope me-2"></i> <?= $user->email ?>
                            </li>
                            <li class="list-group-item">
                                <i class="fas fa-phone me-2"></i> <?= $user->no_telp ?? 'Belum diisi' ?>
                            </li>
                            <li class="list-group-item">
                                <i class="fas fa-map-marker-alt me-2"></i> <?= $user->alamat ?? 'Belum diisi' ?>
                            </li>
                            <li class="list-group-item">
                                <i class="fas fa-user-tag me-2"></i> Username: <?= $user->username ?>
                            </li>
                            <li class="list-group-item">
                                <i class="fas fa-calendar-alt me-2"></i> Bergabung: <?= date('d/m/Y', strtotime($user->created_at)) ?>
                            </li>
                        </ul>
                    </div>
                </div>
                
                <!-- Form Edit Profil -->
                <div class="col-md-8 mb-4">
                    <div class="collapse mb-4" id="editProfileForm">
                        <div class="card">
                            <div class="card-header bg-light">
                                <h5 class="mb-0">Edit Profil</h5>
                            </div>
                            <div class="card-body">
                                <form action="" method="post" enctype="multipart/form-data">
                                    <input type="hidden" name="action" value="update_profile">
                                    
                                    <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" required value="<?= $user->nama_lengkap ?>">
                                    </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" required value="<?= $user->email ?>">
                                    </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>
                                    
                                    <div class="mb-3">
                                        <label for="foto_profil" class="form-label">Foto Profil</label>
                                        <input type="file" class="form-control image-upload" id="foto_profil" name="foto_profil" accept="image/jpeg,image/png,image/jpg" data-preview="preview-foto">
                                        <small class="form-text text-muted">Format: JPG, JPEG, PNG. Maks: 2MB</small>
                                        <div class="mt-2">
                                            <img id="preview-foto" src="<?= SITE_URL ?>/assets/uploads/profile/<?= $user->foto_profil ?? 'default.jpg' ?>" alt="Preview" class="img-thumbnail" style="max-height: 150px">
                                        </div>
                                    </div>
                                    
                                    <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                        <button type="button" class="btn btn-secondary me-md-2" data-bs-toggle="collapse" data-bs-target="#editProfileForm">Batal</button>
                                        <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Form Ganti Password -->
                    <div class="collapse mb-4" id="changePasswordForm">
                        <div class="card">
                            <div class="card-header bg-light">
                                <h5 class="mb-0">Ganti Password</h5>
                            </div>
                            <div class="card-body">
                                <form action="" method="post">
                                    <input type="hidden" name="action" value="change_password">
                                    
                                    <div class="mb-3">
                                        <label for="old_password" class="form-label">Password Lama <span class="text-danger">*</span></label>
                                        <input type="password" class="form-control" id="old_password" name="old_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>
                                        <small class="form-text text-muted">Minimal 6 karakter</small>
                                    </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 d-md-flex justify-content-md-end">
                                        <button type="button" class="btn btn-secondary me-md-2" data-bs-toggle="collapse" data-bs-target="#changePasswordForm">Batal</button>
                                        <button type="submit" class="btn btn-primary">Ganti Password</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Aktivitas Terbaru -->
                    <div class="card">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Aktivitas Terbaru</h5>
                        </div>
                        <div class="card-body">
                            <?php
                            // Ambil log aktivitas terbaru untuk user ini
                            $db->query("SELECT * FROM logs WHERE user_id = :user_id ORDER BY created_at DESC LIMIT 10");
                            $db->bind(':user_id', $id);
                            $logs = $db->resultSet();
                            
                            if (empty($logs)):
                            ?>
                                <p class="text-center py-3">Belum ada aktivitas terbaru</p>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Tanggal</th>
                                                <th>Aktivitas</th>
                                                <th>Deskripsi</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($logs as $log): ?>
                                                <tr>
                                                    <td><?= date('d/m/Y H:i', strtotime($log->created_at)) ?></td>
                                                    <td><?= $log->activity ?></td>
                                                    <td><?= $log->description ?? '-' ?></td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Image Preview
    const imageInput = document.querySelector('.image-upload');
    if (imageInput) {
        imageInput.addEventListener('change', function(event) {
            const preview = document.getElementById(this.dataset.preview);
            if (preview && this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                };
                reader.readAsDataURL(this.files[0]);
            }
        });
    }
});
</script>

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