<?php
/**
 * profil.php - Halaman Profil Wisatawan
 * 
 * ============================================================
 * PERBAIKAN:
 * 1. Menambahkan validasi email
 * 2. Memperbaiki logika update data di database
 * 3. Menambahkan error handling yang lebih baik
 * 4. Memperbaiki path foto
 * ============================================================
 */
include __DIR__ . '/../layouts/header.php';
$activeMenu = 'profil';

// ==============================================
// PROSES UPDATE DATA DIRI
// ==============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['nama'])) {
    $nama = trim($_POST['nama'] ?? '');
    $noHp = trim($_POST['no_hp'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $errors = [];
    
    // Validasi nama
    if (empty($nama)) {
        $errors[] = "Nama lengkap wajib diisi.";
    }
    
    // Validasi nomor HP
    if (empty($noHp)) {
        $errors[] = "Nomor HP wajib diisi.";
    } elseif (!preg_match('/^[0-9]{10,15}$/', $noHp)) {
        $errors[] = "Nomor HP harus berupa angka 10-15 digit.";
    }
    
    // Validasi email
    if (empty($email)) {
        $errors[] = "Email wajib diisi.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Format email tidak valid.";
    }
    
    // Jika ada error, set flash error
    if (!empty($errors)) {
        $_SESSION['flash_error'] = implode(' ', $errors);
        header('Location: ?page=wisatawan&action=profil');
        exit;
    }
    
    // Update ke database
    $userId = $_SESSION['user_id'] ?? 0;
    if ($userId > 0) {
        try {
            // Cek apakah kolom email ada di tabel users
            $stmt = $this->pdo->prepare("SHOW COLUMNS FROM users LIKE 'email'");
            $stmt->execute();
            $hasEmailColumn = $stmt->rowCount() > 0;
            
            if ($hasEmailColumn) {
                $query = "UPDATE users SET nama = ?, no_hp = ?, email = ? WHERE id = ?";
                $stmt = $this->pdo->prepare($query);
                $stmt->execute([$nama, $noHp, $email, $userId]);
            } else {
                $query = "UPDATE users SET nama = ?, no_hp = ? WHERE id = ?";
                $stmt = $this->pdo->prepare($query);
                $stmt->execute([$nama, $noHp, $userId]);
            }
            
            // Update session
            $_SESSION['nama'] = $nama;
            $_SESSION['no_hp'] = $noHp;
            if ($hasEmailColumn) {
                $_SESSION['email'] = $email;
            }
            
            $_SESSION['flash_success'] = '✅ Profil berhasil diperbarui!';
        } catch (PDOException $e) {
            $_SESSION['flash_error'] = 'Gagal memperbarui profil: ' . $e->getMessage();
        }
    } else {
        $_SESSION['flash_error'] = 'User tidak ditemukan. Silakan login kembali.';
    }
    
    header('Location: ?page=wisatawan&action=profil');
    exit;
}

// ==============================================
// PROSES UPLOAD FOTO
// ==============================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['foto_profil']) && $_FILES['foto_profil']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['foto_profil'];
    $allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'image/webp'];
    $maxSize = 2 * 1024 * 1024; // 2MB
    
    // Validasi tipe file
    if (!in_array($file['type'], $allowedTypes)) {
        $_SESSION['flash_error'] = 'Format file tidak didukung. Gunakan JPG, PNG, GIF, atau WebP.';
        header('Location: ?page=wisatawan&action=profil');
        exit;
    }
    
    // Validasi ukuran
    if ($file['size'] > $maxSize) {
        $_SESSION['flash_error'] = 'Ukuran file terlalu besar. Maksimal 2MB.';
        header('Location: ?page=wisatawan&action=profil');
        exit;
    }
    
    // Buat direktori jika belum ada
    $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/reservasi-kapal-wisata/uploads/profil/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    // Generate nama file unik
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $newFileName = 'wisatawan_' . $_SESSION['user_id'] . '_' . time() . '.' . $extension;
    $targetPath = $uploadDir . $newFileName;
    
    // Hapus foto lama jika ada
    if (!empty($_SESSION['foto_profil'])) {
        $oldFile = $uploadDir . $_SESSION['foto_profil'];
        if (file_exists($oldFile)) {
            unlink($oldFile);
        }
    }
    
    // Upload file
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        // Update database
        $userId = $_SESSION['user_id'] ?? 0;
        if ($userId > 0) {
            try {
                $stmt = $this->pdo->prepare("UPDATE users SET foto_profil = ? WHERE id = ?");
                $stmt->execute([$newFileName, $userId]);
            } catch (PDOException $e) {
                $_SESSION['flash_error'] = 'Gagal memperbarui foto di database: ' . $e->getMessage();
                header('Location: ?page=wisatawan&action=profil');
                exit;
            }
        }
        
        $_SESSION['foto_profil'] = $newFileName;
        $_SESSION['flash_success'] = '✅ Foto profil berhasil diperbarui!';
    } else {
        $_SESSION['flash_error'] = 'Gagal mengupload foto. Silakan coba lagi.';
    }
    
    header('Location: ?page=wisatawan&action=profil');
    exit;
}

// ==============================================
// AMBIL DATA DARI SESSION
// ==============================================
$userName = $_SESSION['nama'] ?? 'Pengguna';
$userEmail = $_SESSION['email'] ?? '';
$userNoHp = $_SESSION['no_hp'] ?? '';
$fotoFile = $_SESSION['foto_profil'] ?? null;

// ==============================================
// LOGIKA PATH FOTO
// ==============================================
$baseUrl = defined('BASE_URL') ? rtrim(BASE_URL, '/') : '';
$fotoPath = 'uploads/profil/' . $fotoFile;
$fullPath = $_SERVER['DOCUMENT_ROOT'] . '/reservasi-kapal-wisata/' . $fotoPath;
$fotoExists = !empty($fotoFile) && file_exists($fullPath);

// Buat URL gambar
if ($fotoExists) {
    if (!empty($baseUrl)) {
        $fotoUrl = $baseUrl . '/' . $fotoPath;
    } else {
        $fotoUrl = '/reservasi-kapal-wisata/' . $fotoPath;
    }
} else {
    $fotoUrl = '';
}

// ==============================================
// FLASH MESSAGE
// ==============================================
$flashSuccess = $_SESSION['flash_success'] ?? null;
$flashError = $_SESSION['flash_error'] ?? null;
unset($_SESSION['flash_success'], $_SESSION['flash_error']);
?>

<div class="dashboard-wrapper">
    <?php include __DIR__ . '/../layouts/sidebar_wisatawan.php'; ?>

    <main class="main-content">
        <div class="content-header">
            <h2>👤 Perbaharui Profil</h2>
            <p>Kelola informasi akun Anda. Data yang diperbarui akan segera berlaku.</p>
        </div>

        <!-- FLASH MESSAGE -->
        <?php if($flashSuccess): ?>
            <div class="alert alert-success" id="flashMessage">
                <span class="alert-icon">✅</span>
                <?= htmlspecialchars($flashSuccess) ?>
                <button class="alert-close" onclick="this.parentElement.remove()">✕</button>
            </div>
        <?php endif; ?>
        <?php if($flashError): ?>
            <div class="alert alert-danger" id="flashMessage">
                <span class="alert-icon">❌</span>
                <?= htmlspecialchars($flashError) ?>
                <button class="alert-close" onclick="this.parentElement.remove()">✕</button>
            </div>
        <?php endif; ?>

        <div class="form-card-modern">
            <form method="POST" action="" enctype="multipart/form-data" id="formProfil">
                <input type="hidden" name="action" value="update_profile">

                <!-- FOTO PROFIL -->
                <div class="form-section">
                    <div class="section-title">
                        <span class="section-icon">🖼️</span>
                        <h4>Foto Profil</h4>
                    </div>
                    <div class="profile-photo-wrapper">
                        <div class="current-photo" id="photoContainer">
                            <?php if($fotoExists && !empty($fotoUrl)): ?>
                                <img src="<?= $fotoUrl ?>" 
                                     alt="Foto Profil" 
                                     class="profile-photo-preview" 
                                     id="photoPreview">
                            <?php else: ?>
                                <div class="profile-photo-placeholder" id="photoPreview">
                                    <span style="font-size:3rem;">👤</span>
                                    <span style="font-size:0.8rem; color:var(--gray-400);">Belum ada foto</span>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="photo-upload">
                            <label class="btn btn-secondary btn-upload" style="cursor:pointer;">
                                📷 Ganti Foto
                                <input type="file" name="foto_profil" accept="image/jpeg,image/png,image/jpg,image/gif,image/webp" style="display:none;" onchange="previewPhoto(this)">
                            </label>
                            <span class="helper-text">Format JPG, PNG, GIF, WebP. Maks 2MB.</span>
                            <div id="uploadStatus" style="margin-top:0.5rem;"></div>
                        </div>
                    </div>
                </div>

                <!-- DATA DIRI -->
                <div class="form-section">
                    <div class="section-title">
                        <span class="section-icon">👤</span>
                        <h4>Data Diri</h4>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>Nama Lengkap <span class="required">*</span></label>
                            <input type="text" name="nama" value="<?= htmlspecialchars($userName) ?>" placeholder="Masukkan nama lengkap" required>
                            <span class="helper-text">Nama akan ditampilkan di profil Anda.</span>
                        </div>
                        <div class="form-group">
                            <label>Email <span class="required">*</span></label>
                            <input type="email" name="email" value="<?= htmlspecialchars($userEmail) ?>" placeholder="email@example.com" required>
                            <span class="helper-text">Email digunakan untuk komunikasi penting.</span>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>Nomor WhatsApp <span class="required">*</span></label>
                            <input type="text" name="no_hp" value="<?= htmlspecialchars($userNoHp) ?>" placeholder="0812xxxxxxx" required pattern="[0-9]{10,15}">
                            <span class="helper-text">Pastikan nomor WhatsApp aktif untuk notifikasi.</span>
                        </div>
                        <div class="form-group">
                            <label>Role</label>
                            <input type="text" value="Wisatawan" disabled style="background:var(--gray-100); color:var(--gray-500); cursor:not-allowed;">
                            <span class="helper-text">Anda terdaftar sebagai wisatawan.</span>
                        </div>
                    </div>
                </div>

                <!-- TOMBOL AKSI -->
                <div class="form-actions-modern">
                    <a href="?page=wisatawan&action=dashboard" class="btn btn-secondary btn-lg">
                        <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2">
                            <path d="M19 12H5M12 19l-7-7 7-7"/>
                        </svg>
                        Kembali
                    </a>
                    <button type="submit" class="btn btn-primary btn-lg" id="btnSubmit">
                        <span>💾</span>
                        Simpan Perubahan
                    </button>
                </div>
            </form>
        </div>
    </main>
</div>

<script>
    /**
     * Preview foto sebelum upload
     * Dilengkapi validasi ukuran dan tipe file
     */
    function previewPhoto(input) {
        const preview = document.getElementById('photoPreview');
        const statusDiv = document.getElementById('uploadStatus');
        const container = document.getElementById('photoContainer');
        
        // Reset status
        statusDiv.innerHTML = '';
        statusDiv.className = '';
        
        if (input.files && input.files[0]) {
            const file = input.files[0];
            const maxSize = 2 * 1024 * 1024; // 2MB
            const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif', 'image/webp'];
            
            // Validasi tipe file
            if (!allowedTypes.includes(file.type)) {
                statusDiv.innerHTML = '❌ Format file tidak didukung. Gunakan JPG, PNG, GIF, atau WebP.';
                statusDiv.className = 'error-message';
                input.value = '';
                return;
            }
            
            // Validasi ukuran file
            if (file.size > maxSize) {
                statusDiv.innerHTML = '❌ Ukuran file terlalu besar. Maksimal 2MB.';
                statusDiv.className = 'error-message';
                input.value = '';
                return;
            }
            
            // Preview gambar dengan animasi
            const reader = new FileReader();
            reader.onload = function(e) {
                const img = document.createElement('img');
                img.src = e.target.result;
                img.className = 'profile-photo-preview';
                img.id = 'photoPreview';
                img.style.width = '100%';
                img.style.height = '100%';
                img.style.objectFit = 'cover';
                img.style.animation = 'scaleIn 0.3s ease';
                
                // Ganti konten container
                container.innerHTML = '';
                container.appendChild(img);
                
                // Tampilkan status sukses
                statusDiv.innerHTML = '✅ Foto siap diupload. Klik "Simpan Perubahan" untuk menyimpan.';
                statusDiv.className = 'success-message';
            }
            reader.readAsDataURL(file);
        }
    }

    /**
     * Validasi form sebelum submit
     */
    document.getElementById('formProfil').addEventListener('submit', function(e) {
        const nama = document.querySelector('input[name="nama"]');
        const email = document.querySelector('input[name="email"]');
        const noHp = document.querySelector('input[name="no_hp"]');
        let errors = [];
        
        // Validasi nama
        if (nama.value.trim() === '') {
            errors.push('Nama lengkap wajib diisi.');
            nama.style.borderColor = '#ef4444';
        } else {
            nama.style.borderColor = '';
        }
        
        // Validasi email
        if (email.value.trim() === '') {
            errors.push('Email wajib diisi.');
            email.style.borderColor = '#ef4444';
        } else if (!isValidEmail(email.value.trim())) {
            errors.push('Format email tidak valid.');
            email.style.borderColor = '#ef4444';
        } else {
            email.style.borderColor = '';
        }
        
        // Validasi nomor HP
        if (noHp.value.trim() === '') {
            errors.push('Nomor HP wajib diisi.');
            noHp.style.borderColor = '#ef4444';
        } else if (!/^[0-9]{10,15}$/.test(noHp.value.trim())) {
            errors.push('Nomor HP harus berupa angka 10-15 digit.');
            noHp.style.borderColor = '#ef4444';
        } else {
            noHp.style.borderColor = '';
        }
        
        if (errors.length > 0) {
            e.preventDefault();
            alert('❌ ' + errors.join('\n'));
        } else {
            // Loading state
            const btn = document.getElementById('btnSubmit');
            btn.innerHTML = '⏳ Menyimpan...';
            btn.disabled = true;
            btn.style.opacity = '0.7';
        }
    });

    /**
     * Validasi email
     */
    function isValidEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }

    /**
     * Auto hide flash message setelah 5 detik
     */
    document.addEventListener('DOMContentLoaded', function() {
        const flash = document.getElementById('flashMessage');
        if (flash) {
            setTimeout(function() {
                flash.style.transition = 'all 0.5s ease';
                flash.style.opacity = '0';
                flash.style.transform = 'translateY(-20px)';
                setTimeout(function() {
                    flash.style.display = 'none';
                }, 500);
            }, 5000);
        }
    });

    // Tambahkan animasi keyframes
    const styleSheet = document.createElement("style");
    styleSheet.textContent = `
        @keyframes scaleIn {
            from { opacity: 0; transform: scale(0.8); }
            to { opacity: 1; transform: scale(1); }
        }
        
        .error-message {
            color: #e63946;
            font-size: 0.8rem;
            font-weight: 500;
            padding: 0.3rem 0.6rem;
            background: #fee2e2;
            border-radius: 6px;
            display: inline-block;
        }
        
        .success-message {
            color: #065f46;
            font-size: 0.8rem;
            font-weight: 500;
            padding: 0.3rem 0.6rem;
            background: #d1fae5;
            border-radius: 6px;
            display: inline-block;
        }

        .form-group input.error {
            border-color: #ef4444 !important;
        }
    `;
    document.head.appendChild(styleSheet);
</script>

<style>
    /* ============================================
       LAYOUT
       ============================================ */
    .dashboard-wrapper {
        display: flex;
        gap: 24px;
        max-width: 1200px;
        margin: 1.5rem auto 0;
        padding: 0 20px;
        width: 100%;
        flex: 1;
        align-items: flex-start;
    }
    .main-content {
        flex: 1;
        min-width: 0;
        background: #fff;
        border-radius: 14px;
        padding: 1.8rem;
        box-shadow: 0 4px 20px rgba(0,0,0,0.06);
        border: 1px solid var(--gray-200);
    }
    .content-header {
        margin-bottom: 1.5rem;
    }
    .content-header h2 {
        font-size: 1.4rem;
        font-weight: 700;
        color: var(--gray-900);
        margin-bottom: 0.2rem;
    }
    .content-header p {
        color: var(--gray-500);
        font-size: 0.95rem;
    }

    /* ============================================
       FORM
       ============================================ */
    .form-card-modern {
        background: #fff;
        border-radius: 16px;
        padding: 1.8rem;
    }
    .form-section {
        background: var(--gray-50);
        border-radius: 12px;
        padding: 1.2rem 1.5rem;
        margin-bottom: 1.2rem;
        border: 1px solid var(--gray-200);
        transition: var(--transition);
    }
    .form-section:hover {
        border-color: var(--gray-300);
    }
    .section-title {
        display: flex;
        align-items: center;
        gap: 0.6rem;
        margin-bottom: 1rem;
    }
    .section-title .section-icon { font-size: 1.2rem; }
    .section-title h4 {
        font-size: 0.95rem;
        font-weight: 600;
        color: var(--gray-800);
        margin: 0;
        flex: 1;
    }
    .form-group { margin-bottom: 1rem; }
    .form-group:last-child { margin-bottom: 0; }
    .form-group label {
        display: block;
        font-weight: 600;
        font-size: 0.85rem;
        color: var(--gray-700);
        margin-bottom: 0.3rem;
    }
    .form-group .required {
        color: var(--danger);
    }
    .form-group .helper-text {
        display: block;
        font-size: 0.75rem;
        color: var(--gray-400);
        margin-top: 0.2rem;
    }
    .form-group input {
        width: 100%;
        padding: 0.6rem 0.8rem;
        border: 1.5px solid var(--gray-200);
        border-radius: 8px;
        font-size: 0.9rem;
        background: #fff;
        transition: var(--transition);
    }
    .form-group input:focus {
        outline: none;
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(15,59,94,0.08);
    }
    .form-group input:disabled {
        background: var(--gray-100);
        color: var(--gray-500);
        cursor: not-allowed;
    }
    .form-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 1rem;
    }
    .form-actions-modern {
        display: flex;
        gap: 1rem;
        margin-top: 1.5rem;
        padding-top: 1rem;
        border-top: 1px solid var(--gray-200);
    }

    /* ============================================
       BUTTON
       ============================================ */
    .btn {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.5rem 1rem;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        font-size: 0.85rem;
        cursor: pointer;
        transition: var(--transition);
        text-decoration: none;
    }
    .btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    .btn-primary { 
        background: var(--primary-gradient, #0d3b66); 
        color: #fff; 
    }
    .btn-primary:hover { 
        background: var(--primary-light, #1a5276); 
        color: #fff; 
    }
    .btn-secondary { 
        background: var(--gray-200); 
        color: var(--gray-700); 
    }
    .btn-secondary:hover { 
        background: var(--gray-300); 
        color: var(--gray-800); 
    }
    .btn-lg { 
        padding: 0.7rem 1.5rem; 
        font-size: 0.95rem; 
        border-radius: 10px;
    }
    .btn-upload {
        background: var(--gray-200);
        padding: 0.5rem 1.2rem;
        font-size: 0.85rem;
        border-radius: 8px;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        transition: var(--transition);
    }
    .btn-upload:hover {
        background: var(--gray-300);
        transform: translateY(-2px);
    }

    /* ============================================
       FOTO PROFIL
       ============================================ */
    .profile-photo-wrapper {
        display: flex;
        align-items: center;
        gap: 2rem;
        flex-wrap: wrap;
    }
    .current-photo {
        width: 130px;
        height: 130px;
        border-radius: 50%;
        overflow: hidden;
        border: 3px solid var(--gray-200);
        flex-shrink: 0;
        background: var(--gray-100);
        display: flex;
        align-items: center;
        justify-content: center;
        transition: var(--transition);
        position: relative;
    }
    .current-photo:hover {
        border-color: var(--primary);
        box-shadow: 0 0 0 4px rgba(13, 59, 102, 0.1);
    }
    .current-photo::after {
        content: '📷';
        position: absolute;
        bottom: 5px;
        right: 5px;
        background: var(--primary);
        color: #fff;
        border-radius: 50%;
        padding: 4px;
        font-size: 0.8rem;
        opacity: 0;
        transition: var(--transition);
    }
    .current-photo:hover::after {
        opacity: 1;
    }
    .profile-photo-preview {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
    }
    .profile-photo-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: var(--gray-400);
        font-size: 0.8rem;
        text-align: center;
        padding: 10px;
        background: linear-gradient(135deg, var(--gray-100), var(--gray-200));
    }
    .photo-upload {
        display: flex;
        flex-direction: column;
        gap: 0.3rem;
        flex: 1;
    }

    /* ============================================
       ALERT
       ============================================ */
    .alert {
        padding: 0.8rem 1.2rem;
        border-radius: 10px;
        margin-bottom: 1.2rem;
        font-weight: 500;
        border-left: 4px solid transparent;
        transition: all 0.5s ease;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .alert-success {
        background: #d1fae5;
        color: #065f46;
        border-left-color: var(--success);
    }
    .alert-danger {
        background: #fee2e2;
        color: #991b1b;
        border-left-color: var(--danger);
    }
    .alert-icon { font-size: 1.2rem; }
    .alert-close {
        margin-left: auto;
        background: none;
        border: none;
        font-size: 1rem;
        cursor: pointer;
        color: inherit;
        opacity: 0.6;
        padding: 0 4px;
        transition: var(--transition);
    }
    .alert-close:hover { opacity: 1; }

    /* ============================================
       RESPONSIVE
       ============================================ */
    @media (max-width: 768px) {
        .dashboard-wrapper { 
            flex-direction: column; 
            padding: 0 12px; 
            margin-top: 1rem; 
        }
        .main-content { 
            padding: 1rem; 
        }
        .form-row { 
            grid-template-columns: 1fr; 
            gap: 0.5rem; 
        }
        .form-card-modern { 
            padding: 1rem; 
        }
        .form-section { 
            padding: 0.8rem 1rem; 
        }
        .form-actions-modern { 
            flex-direction: column; 
        }
        .form-actions-modern .btn {
            justify-content: center;
        }
        .profile-photo-wrapper { 
            flex-direction: column; 
            align-items: center; 
            text-align: center; 
        }
        .current-photo { 
            width: 110px; 
            height: 110px; 
        }
        .photo-upload {
            align-items: center;
        }
    }
    @media (max-width: 480px) {
        .current-photo { 
            width: 90px; 
            height: 90px; 
        }
        .content-header h2 {
            font-size: 1.2rem;
        }
    }
</style>

<?php include __DIR__ . '/../layouts/footer.php'; ?>