<?php
// pengawas/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 pengawas
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'pengawas') {
    // Redirect ke halaman login jika belum login atau bukan pengawas
    setFlash('login_required', 'Anda harus login sebagai pengawas 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();

// 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 input
    $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';
    }
    
    // Cek apakah email sudah digunakan user lain
    if ($email !== $user->email) {
        $db->query("SELECT * FROM users WHERE email = :email AND id != :id");
        $db->bind(':email', $email);
        $db->bind(':id', $_SESSION['user_id']);
        $email_exists = $db->single();
        
        if ($email_exists) {
            $errors[] = 'Email sudah digunakan oleh user 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 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'], 'Pengawas memperbarui profil');
            
            setFlash('profile', 'Profil berhasil diperbarui', 'success');
            header('Location: ' . SITE_URL . '/pengawas/profil/index.php');
            exit;
        } else {
            setFlash('profile', 'Gagal memperbarui profil', 'danger');
        }
    } else {
        // Tampilkan error
        setFlash('profile', implode('<br>', $errors), 'danger');
    }
}

// Proses update password
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_password'])) {
    $old_password = $_POST['old_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Validasi input
    $errors = [];
    
    if (empty($old_password)) {
        $errors[] = 'Password lama harus diisi';
    }
    
    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';
    }
    
    // Verifikasi password lama
    if (!password_verify($old_password, $user->password)) {
        $errors[] = 'Password lama tidak sesuai';
    }
    
    // Jika tidak ada error, update password
    if (empty($errors)) {
        $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
        
        $db->query("UPDATE users SET password = :password WHERE id = :id");
        $db->bind(':password', $password_hash);
        $db->bind(':id', $_SESSION['user_id']);
        
        if ($db->execute()) {
            // Log aktivitas
            logActivity('Update password', 'user', $_SESSION['user_id'], 'Pengawas memperbarui password');
            
            setFlash('profile', 'Password berhasil diperbarui', 'success');
            header('Location: ' . SITE_URL . '/pengawas/profil/index.php');
            exit;
        } else {
            setFlash('profile', 'Gagal memperbarui password', 'danger');
        }
    } else {
        // Tampilkan error
        setFlash('profile', implode('<br>', $errors), 'danger');
    }
}

// Proses update foto profil
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_photo'])) {
    if (isset($_FILES['foto_profil']) && $_FILES['foto_profil']['error'] == 0) {
        $foto = $_FILES['foto_profil'];
        $upload_dir = UPLOAD_DIR . 'profile/';
        
        // Upload foto profil
        $result = uploadFile($foto, $upload_dir, 'gambar');
        
        if ($result) {
            // Hapus foto lama jika bukan default
            if ($user->foto_profil != 'default.jpg' && file_exists($upload_dir . $user->foto_profil)) {
                unlink($upload_dir . $user->foto_profil);
            }
            
            // Update foto profil di database
            $db->query("UPDATE users SET foto_profil = :foto_profil WHERE id = :id");
            $db->bind(':foto_profil', $result);
            $db->bind(':id', $_SESSION['user_id']);
            
            if ($db->execute()) {
                // Log aktivitas
                logActivity('Update foto profil', 'user', $_SESSION['user_id'], 'Pengawas memperbarui foto profil');
                
                setFlash('profile', 'Foto profil berhasil diperbarui', 'success');
                header('Location: ' . SITE_URL . '/pengawas/profil/index.php');
                exit;
            } else {
                setFlash('profile', 'Gagal memperbarui foto profil', 'danger');
            }
        }
    } else {
        setFlash('profile', 'Pilih foto profil terlebih dahulu', '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 ?>/pengawas/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 ?>/pengawas/audit/index.php"> -->
                            <!-- <i class="fas fa-search-dollar me-2"></i> -->
                            <!-- Audit Transaksi -->
                        <!-- </a> -->
                    <!-- </li> -->
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/pengawas/laporan/index.php">
                            <i class="fas fa-file-alt me-2"></i>
                            Laporan Keuangan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/pengawas/logs/index.php">
                            <i class="fas fa-history me-2"></i>
                            Log Aktivitas
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/pengawas/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>

            <?php flash(); ?>

            <div class="row">
                <!-- Foto Profil -->
                <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' ?>" class="img-fluid rounded-circle profile-img mb-3" alt="Foto Profil" 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>
                            
                            <!-- Form Update Foto Profil -->
                            <form action="" method="post" enctype="multipart/form-data" class="mt-3">
                                <div class="mb-3">
                                    <label for="foto_profil" class="form-label">Update Foto Profil</label>
                                    <input class="form-control form-control-sm" id="foto_profil" name="foto_profil" type="file" accept="image/*">
                                    <small class="form-text text-muted">Format: JPG, JPEG, PNG. Maks: 2MB</small>
                                </div>
                                <button type="submit" name="update_photo" class="btn btn-outline-primary btn-sm">
                                    <i class="fas fa-camera me-1"></i> Ganti Foto
                                </button>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Info Akun -->
                    <div class="card mt-4">
                        <div class="card-header bg-white">
                            <h5 class="card-title mb-0">Informasi Akun</h5>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label fw-bold">Username</label>
                                <p><?= $user->username ?></p>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">Role</label>
                                <p><?= getRoleName($user->role) ?></p>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">Terdaftar Sejak</label>
                                <p><?= date('d F Y', strtotime($user->created_at)) ?></p>
                            </div>
                            <div class="mb-0">
                                <label class="form-label fw-bold">Update Terakhir</label>
                                <p><?= date('d F Y H:i', strtotime($user->updated_at)) ?></p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Form Edit Profil -->
                <div class="col-md-8">
                    <div class="card">
                        <div class="card-header bg-white">
                            <h5 class="card-title mb-0">Edit Profil</h5>
                        </div>
                        <div class="card-body">
                            <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">
                                    <i class="fas fa-save me-1"></i> Simpan Perubahan
                                </button>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Form Ganti Password -->
                    <div class="card mt-4">
                        <div class="card-header bg-white">
                            <h5 class="card-title mb-0">Ganti Password</h5>
                        </div>
                        <div class="card-body">
                            <form action="" method="post">
                                <div class="mb-3">
                                    <label for="old_password" class="form-label">Password Lama</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</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</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">
                                    <i class="fas fa-key me-1"></i> Ganti Password
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
// Preview image sebelum upload
document.getElementById('foto_profil').addEventListener('change', function(e) {
    const reader = new FileReader();
    reader.onload = function(e) {
        document.querySelector('.profile-img').src = e.target.result;
    }
    reader.readAsDataURL(this.files[0]);
});
</script>

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