<?php
// user/profil/index.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$pageTitle = 'Profil Saya';
require_once '../../includes/config.php';
require_once '../../includes/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';
// Atur batas eksekusi dan memori
ini_set('max_execution_time', 300); // 5 menit
ini_set('memory_limit', '256M');    // 256 MB memori
// Mulai session jika belum dimulai
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

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

$user_id = $_SESSION['user_id'];
$db = dbConnect();

// Membuat instance Auth untuk menggunakan logActivity
$auth = new Auth();

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

if (!$user) {
    setFlash('profil', 'Data user tidak ditemukan', 'danger');
    header('Location: ' . SITE_URL . '/auth/logout.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']);
    
    $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', $user_id);
        
        if ($db->rowCount() > 0) {
            $errors[] = 'Email sudah digunakan user lain';
        }
    }
    
    if (empty($errors)) {
        // Update database
        $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', $user_id);
        
        if ($db->execute()) {
            // Update session
            $_SESSION['nama_lengkap'] = $nama_lengkap;
            $_SESSION['email'] = $email;
            $_SESSION['flash'] = [
        'name' => 'profil',
        'message' => 'Password berhasil diubah',
        'type' => 'success'
    ];
    
            
            // Log aktivitas menggunakan metode dari Auth class
            // $auth->logActivity($user_id, 'Update profil', 'user', $user_id, 'User mengupdate profil');
            
            setFlash('profil', 'Profil berhasil diupdate', 'success');
            echo "<script>window.location.href = '".SITE_URL."/user/profil/index.php?t=".time()."';</script>";
    exit;
            exit;
        } else {
            setFlash('profil', 'Gagal update profil', 'danger');
        }
    } else {
        $error_message = implode('<br>', $errors);
        setFlash('profil', $error_message, 'danger');
    }
}

// Proses ganti password
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['change_password'])) {
    $old_password = $_POST['old_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    $errors = [];
    
    // Cek password lama
    if (!password_verify($old_password, $user->password)) {
        $errors[] = 'Password lama salah';
    }
    
    // Validasi password baru
    if (empty($new_password)) {
        $errors[] = 'Password baru harus diisi';
    } elseif (strlen($new_password) < 6) {
        $errors[] = 'Password minimal 6 karakter';
    }
    
    // Cek konfirmasi password
    if ($new_password != $confirm_password) {
        $errors[] = 'Konfirmasi password tidak sesuai';
    }
    
    if (empty($errors)) {
        // Hash password baru
        $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
        
        // Update database
        $db->query("UPDATE users SET password = :password WHERE id = :id");
        $db->bind(':password', $password_hash);
        $db->bind(':id', $user_id);
        
        if ($db->execute()) {
            // Log aktivitas menggunakan metode dari Auth class
            // $auth->logActivity($user_id, 'Ganti password', 'user', $user_id, 'User mengganti password');
            
            setFlash('profil', 'Password berhasil diubah', 'success');
            header('Location: ' . SITE_URL . '/user/profil/index.php');
            exit;
        } else {
            setFlash('profil', 'Gagal update password', 'danger');
        }
    } else {
        $error_message = implode('<br>', $errors);
        setFlash('profil', $error_message, 'danger');
    }
}

// Proses upload foto profil
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_photo'])) {
    try {
        // Cek apakah ada file yang diupload
        if (isset($_FILES['foto_profil']) && $_FILES['foto_profil']['error'] == 0) {
            // Direktori untuk menyimpan foto profil
            $upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/donasi/assets/uploads/profile/';
            
            // Pastikan folder ada
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            // Upload file
            $file = $_FILES['foto_profil'];
            $file_name = $file['name'];
            $file_tmp = $file['tmp_name'];
            $file_size = $file['size'];
            
            // Cek ekstensi file
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            $allowed_ext = ['jpg', 'jpeg', 'png'];
            
            if (in_array($file_ext, $allowed_ext)) {
                // Cek ukuran file (maks 2MB)
                if ($file_size <= 2097152) {
                    // Generate nama file baru untuk menghindari duplikasi
                    $new_file_name = 'profile_' . $user_id . '_' . time() . '.' . $file_ext;
                    $destination = $upload_dir . $new_file_name;
                    
                    // Upload file
                    if (move_uploaded_file($file_tmp, $destination)) {
                        // Cek jika ada foto profil lama, hapus file (kecuali default.jpg)
                        if (!empty($user->foto_profil) && $user->foto_profil != 'default.jpg') {
                            $old_file = $upload_dir . $user->foto_profil;
                            if (file_exists($old_file)) {
                                @unlink($old_file); // Gunakan @ untuk menekan pesan error
                            }
                        }
                        
                        // Update database
                        $db->query("UPDATE users SET foto_profil = :foto_profil WHERE id = :id");
                        $db->bind(':foto_profil', $new_file_name);
                        $db->bind(':id', $user_id);
                        
                        if ($db->execute()) {
                            // Log aktivitas (opsional, hapus jika masih menyebabkan error)
                            // $auth->logActivity($user_id, 'Upload foto profil', 'user', $user_id, 'User mengupload foto profil baru');
                            
                            setFlash('profil', 'Foto profil berhasil diupload', 'success');
                            header('Location: ' . SITE_URL . '/user/profil/index.php');
                            exit;
                        } else {
                            setFlash('profil', 'Gagal update database', 'danger');
                        }
                    } else {
                        setFlash('profil', 'Gagal upload file', 'danger');
                    }
                } else {
                    setFlash('profil', 'Ukuran file terlalu besar (maks 2MB)', 'danger');
                }
            } else {
                setFlash('profil', 'Ekstensi file tidak diizinkan (hanya jpg, jpeg, png)', 'danger');
            }
        } else {
            setFlash('profil', 'Silakan pilih file foto profil', 'danger');
        }
    } catch (Exception $e) {
        setFlash('profil', 'Error: ' . $e->getMessage(), 'danger');
    }
}

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

<!-- Sidebar & Content -->
<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 ?>/user/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 ?>/user/donasi/index.php">
                            <i class="fas fa-donate me-2"></i>
                            Donasi Saya
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/user/donasi/buat.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Buat Donasi
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/user/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/<?= !empty($user->foto_profil) ? $user->foto_profil : 'default.jpg' ?>" class="rounded-circle img-thumbnail mb-3" alt="Foto Profil" style="width: 150px; height: 150px; object-fit: cover;">
                            
                            <h5 class="card-title"><?= $user->nama_lengkap ?></h5>
                            <p class="text-muted"><?= ucfirst($user->role) ?></p>
                            
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#uploadPhotoModal">
                                <i class="fas fa-camera me-1"></i> Ganti Foto Profil
                            </button>
                        </div>
                        
                        <div class="card-footer bg-light">
                            <div class="d-flex justify-content-between align-items-center">
                                <span><i class="fas fa-calendar-alt me-1"></i> Bergabung:</span>
                                <span><?= date('d/m/Y', strtotime($user->created_at)) ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Statistik Donasi -->
                    <div class="card mt-4">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Statistik Donasi</h5>
                        </div>
                        <div class="card-body">
                            <?php
                            // Query untuk statistik donasi
                            $db->query("SELECT 
                                       COUNT(*) as total_donasi, 
                                       SUM(CASE WHEN status = 'diverifikasi' THEN jumlah ELSE 0 END) as total_nominal,
                                       COUNT(DISTINCT kampanye_id) as total_kampanye
                                       FROM donasi 
                                       WHERE user_id = :user_id");
                            $db->bind(':user_id', $user_id);
                            $stats = $db->single();
                            ?>
                            
                            <div class="row text-center">
                                <div class="col-4">
                                    <h4 class="mb-0"><?= $stats->total_donasi ?? 0 ?></h4>
                                    <small class="text-muted">Total Donasi</small>
                                </div>
                                <div class="col-4">
                                    <h4 class="mb-0"><?= rupiah($stats->total_nominal ?? 0) ?></h4>
                                    <small class="text-muted">Nominal</small>
                                </div>
                                <div class="col-4">
                                    <h4 class="mb-0"><?= $stats->total_kampanye ?? 0 ?></h4>
                                    <small class="text-muted">Kampanye</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Tab Informasi Profil -->
                <div class="col-md-8 mb-4">
                    <div class="card">
                        <div class="card-header bg-light">
                            <ul class="nav nav-tabs card-header-tabs" id="profileTabs" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="info-tab" data-bs-toggle="tab" data-bs-target="#info" type="button" role="tab" aria-controls="info" aria-selected="true">Informasi Profil</button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="password-tab" data-bs-toggle="tab" data-bs-target="#password" type="button" role="tab" aria-controls="password" aria-selected="false">Ganti Password</button>
                                </li>
                            </ul>
                        </div>
                        <div class="card-body">
                            <div class="tab-content" id="profileTabsContent">
                                <!-- Tab Informasi Profil -->
                                <div class="tab-pane fade show active" id="info" role="tabpanel" aria-labelledby="info-tab">
                                    <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 ?>" disabled>
                                            <small class="text-muted">Username tidak dapat diubah</small>
                                        </div>
                                        
                                        <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">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>
                                        
                                        <button type="submit" name="update_profile" class="btn btn-primary">Update Profil</button>
                                    </form>
                                </div>
                                
                                <!-- Tab Ganti Password -->
                                <div class="tab-pane fade" id="password" role="tabpanel" aria-labelledby="password-tab">
                                    <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="text-muted">Password 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="change_password" class="btn btn-primary">Ganti Password</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Modal Upload Foto Profil -->
<div class="modal fade" id="uploadPhotoModal" tabindex="-1" aria-labelledby="uploadPhotoModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="uploadPhotoModalLabel">Upload Foto Profil</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form action="" method="post" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="foto_profil" class="form-label">Pilih Foto</label>
                        <input type="file" class="form-control" id="foto_profil" name="foto_profil" accept=".jpg, .jpeg, .png" required>
                        <small class="text-muted">Format: JPG, JPEG, PNG (maks 2MB)</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Preview</label>
                        <div class="border p-3 rounded text-center">
                            <img id="preview_image" src="<?= SITE_URL ?>/assets/img/no-image.jpg" alt="Preview" class="img-fluid rounded-circle" style="max-height: 200px; max-width: 200px;">
                        </div>
                    </div>
                    
                    <div class="d-grid">
                        <button type="submit" name="upload_photo" class="btn btn-primary">Upload Foto</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Preview gambar saat dipilih
    const fotoProfil = document.getElementById('foto_profil');
    const previewImage = document.getElementById('preview_image');
    
    if (fotoProfil && previewImage) {
        fotoProfil.addEventListener('change', function() {
            const file = this.files[0];
            if (file) {
                const reader = new FileReader();
                
                reader.addEventListener('load', function() {
                    previewImage.setAttribute('src', this.result);
                });
                
                reader.readAsDataURL(file);
            } else {
                previewImage.setAttribute('src', '<?= SITE_URL ?>/assets/img/no-image.jpg');
            }
        });
    }
});
</script>

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