<?php
session_start();
include '../config/koneksi.php';
$isLogin = isset($_SESSION['user_id']);
if(!isset($_SESSION['user_id'])){
    header('Location: login.php');
    exit;
}
$userId = $_SESSION['user_id'];
$userNama = $_SESSION['user_nama'];
$activePage = '';

// Cek apakah kolom foto ada di tabel user
$checkColumn = mysqli_query($conn, "SHOW COLUMNS FROM user LIKE 'foto'");
$hasFotoColumn = mysqli_num_rows($checkColumn) > 0;

// Jika kolom foto belum ada, tambahkan
if(!$hasFotoColumn) {
    $addColumn = mysqli_query($conn, "ALTER TABLE user ADD COLUMN foto VARCHAR(255) DEFAULT NULL");
    if($addColumn) {
        $hasFotoColumn = true;
    }
}

// Ambil data user SEBELUM include header.php
$q = mysqli_query($conn, "SELECT * FROM user WHERE id=$userId");
$user = mysqli_fetch_assoc($q);

// Sekarang include header.php dengan data user yang sudah lengkap
include 'header.php';

// Proses update profil
if(isset($_POST['update'])){
    $nama = mysqli_real_escape_string($conn, $_POST['nama']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $alamat = mysqli_real_escape_string($conn, $_POST['alamat']);
    $telepon = mysqli_real_escape_string($conn, $_POST['telepon']);
    $cek = mysqli_query($conn, "SELECT id FROM user WHERE email='$email' AND id!=$userId");
    if(mysqli_num_rows($cek)==0){
        mysqli_query($conn, "UPDATE user SET nama='$nama', email='$email', alamat='$alamat', telepon='$telepon' WHERE id=$userId");
        $_SESSION['user_nama'] = $nama;
        echo '<div class="alert-success" style="background:#d4edda;color:#155724;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Profil berhasil diupdate!</div>';
    } else {
        echo '<div class="alert-error" style="background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Email sudah digunakan!</div>';
    }
}

// Proses ganti password
if(isset($_POST['ganti_pass'])){
    $pass1 = $_POST['pass1'];
    $pass2 = $_POST['pass2'];
    if(strlen($pass1)<6){
        echo '<div class="alert-error" style="background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Password minimal 6 karakter!</div>';
    } else if($pass1!=$pass2){
        echo '<div class="alert-error" style="background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Konfirmasi password tidak sama!</div>';
    } else {
        $hash = password_hash($pass1, PASSWORD_DEFAULT);
        mysqli_query($conn, "UPDATE user SET password='$hash' WHERE id=$userId");
        echo '<div class="alert-success" style="background:#d4edda;color:#155724;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Password berhasil diganti!</div>';
    }
}

// Proses upload foto profil
if(isset($_POST['upload_foto']) && isset($_FILES['foto']) && $_FILES['foto']['error'] == 0 && $hasFotoColumn){
    $file = $_FILES['foto'];
    $fileName = $file['name'];
    $fileSize = $file['size'];
    $fileTmp = $file['tmp_name'];
    $fileType = $file['type'];
    
    // Validasi ukuran file (max 5MB)
    if($fileSize > 5 * 1024 * 1024) {
        echo '<div class="alert-error" style="background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Ukuran file terlalu besar! Maksimal 5MB.</div>';
    } else {
        // Validasi tipe file
        $allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        if(!in_array($fileType, $allowedTypes)) {
            echo '<div class="alert-error" style="background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Tipe file tidak didukung! Gunakan JPG, PNG, atau GIF.</div>';
        } else {
            // Generate nama file unik
            $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
            $newFileName = 'user_' . $userId . '_' . time() . '.' . $ext;
            $uploadPath = '../assets/images/profile/' . $newFileName;
            
            // Hapus foto lama jika ada
            if(isset($user['foto']) && $user['foto'] && file_exists('../assets/images/profile/' . $user['foto'])) {
                unlink('../assets/images/profile/' . $user['foto']);
            }
            
            // Upload file baru
            if(move_uploaded_file($fileTmp, $uploadPath)) {
                // Update database
                $updateQuery = mysqli_query($conn, "UPDATE user SET foto='$newFileName' WHERE id=$userId");
                if($updateQuery) {
                    echo '<div class="alert-success" style="background:#d4edda;color:#155724;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Foto profil berhasil diupload!</div>';
                    $user['foto'] = $newFileName;
                    // Update session untuk refresh header
                    $_SESSION['user_foto'] = $newFileName;
                    
                    // Redirect setelah 1 detik untuk refresh halaman
                    echo '<script>
                        setTimeout(function() {
                            window.location.href = "profile.php";
                        }, 1000);
                    </script>';
                } else {
                    echo '<div class="alert-error" style="background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Gagal menyimpan data foto ke database!</div>';
                }
            } else {
                echo '<div class="alert-error" style="background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Gagal upload foto! Pastikan folder memiliki permission yang benar.</div>';
            }
        }
    }
} elseif(isset($_POST['upload_foto']) && !$hasFotoColumn) {
    echo '<div class="alert-error" style="background:#f8d7da;color:#721c24;padding:12px;border-radius:8px;margin:10px 0;position:fixed;top:20px;right:20px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,0.15);">Fitur upload foto belum tersedia. Silakan hubungi administrator.</div>';
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Profil User - Ang Mansion</title>
    <link rel="stylesheet" type="text/css" href="../assets/style_user.css">
    <style>
        .profile-avatar-container {
            text-align: center;
            margin-bottom: 20px;
        }
        .profile-avatar {
            width: 120px;
            height: 120px;
            border-radius: 50%;
            object-fit: cover;
            border: 4px solid #2563eb;
            background: #e0e7ff;
            box-shadow: 0 4px 12px rgba(37,99,235,0.15);
            transition: transform 0.3s ease;
        }
        .profile-avatar:hover {
            transform: scale(1.05);
        }
        .upload-form {
            background: #f8fafc;
            padding: 20px;
            border-radius: 12px;
            border: 2px dashed #cbd5e1;
            margin-bottom: 20px;
        }
        .upload-form:hover {
            border-color: #2563eb;
            background: #f1f5f9;
        }
        .file-input-wrapper {
            position: relative;
            display: inline-block;
            width: 100%;
        }
        .file-input-wrapper input[type=file] {
            width: 100%;
            padding: 10px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            background: white;
            cursor: pointer;
        }
        .file-input-wrapper input[type=file]:focus {
            outline: none;
            border-color: #2563eb;
            box-shadow: 0 0 0 3px rgba(37,99,235,0.1);
        }
        .btn-upload {
            background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
            color: white;
            border: none;
            border-radius: 8px;
            padding: 12px 24px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            margin-top: 10px;
        }
        .btn-upload:hover {
            background: linear-gradient(135deg, #1d4ed8 0%, #1e40af 100%);
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(37,99,235,0.3);
        }
        .alert-success, .alert-error {
            animation: slideIn 0.3s ease-out;
        }
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        @keyframes slideOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
        .alert-success.fade-out, .alert-error.fade-out {
            animation: slideOut 0.3s ease-in forwards;
        }
    </style>
</head>
<body>
<div class="hero" style="font-size:2em;">
    <span style="color:#ffe600;">&gt;&gt;Profil User</span>
</div>

<div class="profile-main-container">
    <div class="profile-card">
        <div class="profile-title">Informasi Profil</div>
        <form method="post" class="profile-form">
            <div class="mb-3">
                <label for="nama" class="form-label">Nama Lengkap</label>
                <input type="text" class="form-control" id="nama" name="nama" value="<?php echo htmlspecialchars($user['nama']); ?>" 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="<?php echo htmlspecialchars($user['email']); ?>" required>
            </div>
            <div class="mb-3">
                <label for="alamat" class="form-label">Alamat</label>
                <input type="text" class="form-control" id="alamat" name="alamat" value="<?php echo htmlspecialchars($user['alamat']); ?>" required>
            </div>
            <div class="mb-3">
                <label for="telepon" class="form-label">Telepon</label>
                <input type="text" class="form-control" id="telepon" name="telepon" value="<?php echo htmlspecialchars($user['telepon']); ?>" required>
            </div>
            <button type="submit" name="update" class="btn btn-primary">Update Profil</button>
        </form>
    </div>

    <div class="profile-card">
        <div class="profile-title">Ganti Password</div>
        <form method="post" class="profile-form">
            <div class="mb-3">
                <label for="pass1" class="form-label">Password Baru</label>
                <input type="password" class="form-control" id="pass1" name="pass1" required>
            </div>
            <div class="mb-3">
                <label for="pass2" class="form-label">Konfirmasi Password</label>
                <input type="password" class="form-control" id="pass2" name="pass2" required>
            </div>
            <button type="submit" name="ganti_pass" class="btn btn-warning">Ganti Password</button>
        </form>
    </div>

    <div class="profile-card">
        <div class="profile-title">Foto Profil</div>
        <div class="profile-avatar-container">
            <img class="profile-avatar" src="<?php echo isset($user['foto']) && $user['foto'] ? '../assets/images/profile/'.htmlspecialchars($user['foto']) : '../assets/images/LogoAngMansion-Putih.png'; ?>" alt="Foto Profil">
        </div>
        
        <?php if($hasFotoColumn): ?>
        <form method="post" enctype="multipart/form-data" class="upload-form">
            <div class="file-input-wrapper">
                <input type="file" name="foto" accept="image/*" required>
            </div>
            <button type="submit" name="upload_foto" class="btn-upload">
                📷 Upload Foto Profil
            </button>
            <div style="margin-top: 10px; font-size: 0.85em; color: #666;">
                <strong>Ketentuan:</strong><br>
                • Format: JPG, PNG, GIF<br>
                • Ukuran maksimal: 5MB<br>
                • Foto akan otomatis di-crop menjadi persegi
            </div>
        </form>
        <?php else: ?>
        <div style="text-align: center; padding: 20px; background: #f8f9fa; border-radius: 8px;">
            <p style="color: #666; margin: 0;">Fitur upload foto belum tersedia. Silakan hubungi administrator.</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<div class="footer">
    Copyright &copy; 2025 | Ang Mansion
</div>

<script>
// Auto hide alerts after 3 seconds
document.addEventListener('DOMContentLoaded', function() {
    const alerts = document.querySelectorAll('.alert-success, .alert-error');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            alert.classList.add('fade-out');
            setTimeout(function() {
                alert.remove();
            }, 300);
        }, 3000);
    });
});

// Prevent scroll to top on form submission
document.addEventListener('DOMContentLoaded', function() {
    const forms = document.querySelectorAll('form');
    forms.forEach(function(form) {
        form.addEventListener('submit', function(e) {
            // Store current scroll position
            sessionStorage.setItem('scrollPosition', window.pageYOffset);
        });
    });
    
    // Restore scroll position after page load
    const scrollPosition = sessionStorage.getItem('scrollPosition');
    if (scrollPosition) {
        window.scrollTo(0, parseInt(scrollPosition));
        sessionStorage.removeItem('scrollPosition');
    }
});
</script>
</body>
</html> 