<?php
require_once '../includes/config.php';
$pageTitle = "Profil Saya";

// Check if user is logged in
if (!isUserLoggedIn()) {
    redirect(SITE_URL . 'user/login.php');
}

$user_id = $_SESSION['user_id'];
$success = false;
$error = '';

try {
    $conn = connectDB();
    
    // Get user information
    $stmt = $conn->prepare("SELECT * FROM users WHERE user_id = :user_id");
    $stmt->bindParam(':user_id', $user_id);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Process profile update
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $name = sanitize($_POST['name']);
        $email = sanitize($_POST['email']);
        $address = sanitize($_POST['address']);
        $phone = sanitize($_POST['phone']);
        $current_password = $_POST['current_password'] ?? '';
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        
        // Validate input
        if (empty($name)) {
            $error = 'Nama lengkap harus diisi';
        } elseif (empty($email)) {
            $error = 'Email harus diisi';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Format email tidak valid';
        } else {
            // Check if email already exists (except for current user)
            $stmt = $conn->prepare("SELECT * FROM users WHERE email = :email AND user_id != :user_id");
            $stmt->bindParam(':email', $email);
            $stmt->bindParam(':user_id', $user_id);
            $stmt->execute();
            
            if ($stmt->fetch(PDO::FETCH_ASSOC)) {
                $error = 'Email sudah terdaftar. Silakan gunakan email lain';
            } else {
                // Check if password is being updated
                if (!empty($current_password)) {
                    // Verify current password
                    if (!password_verify($current_password, $user['password'])) {
                        $error = 'Password saat ini tidak valid';
                    } elseif (empty($new_password)) {
                        $error = 'Password baru harus diisi';
                    } elseif ($new_password !== $confirm_password) {
                        $error = 'Password baru dan konfirmasi password tidak cocok';
                    } elseif (strlen($new_password) < 6) {
                        $error = 'Password baru minimal 6 karakter';
                    }
                }
                
                if (empty($error)) {
                    // Update user profile
                    if (!empty($current_password) && !empty($new_password)) {
                        // Update with new password
                        $hashedPassword = password_hash($new_password, PASSWORD_DEFAULT);
                        $stmt = $conn->prepare("UPDATE users SET name = :name, email = :email, password = :password, address = :address, phone = :phone WHERE user_id = :user_id");
                        $stmt->bindParam(':password', $hashedPassword);
                    } else {
                        // Update without changing password
                        $stmt = $conn->prepare("UPDATE users SET name = :name, email = :email, address = :address, phone = :phone WHERE user_id = :user_id");
                    }
                    
                    $stmt->bindParam(':name', $name);
                    $stmt->bindParam(':email', $email);
                    $stmt->bindParam(':address', $address);
                    $stmt->bindParam(':phone', $phone);
                    $stmt->bindParam(':user_id', $user_id);
                    
                    if ($stmt->execute()) {
                        $success = true;
                        
                        // Update session variables
                        $_SESSION['user_name'] = $name;
                        
                        // Refresh user data
                        $stmt = $conn->prepare("SELECT * FROM users WHERE user_id = :user_id");
                        $stmt->bindParam(':user_id', $user_id);
                        $stmt->execute();
                        $user = $stmt->fetch(PDO::FETCH_ASSOC);
                    } else {
                        $error = 'Terjadi kesalahan saat memperbarui profil';
                    }
                }
            }
        }
    }
} catch (PDOException $e) {
    $error = "Error: " . $e->getMessage();
}

include '../includes/header.php';
?>

<div class="profile-page">
    <div class="container">
        <h1>Profil Saya</h1>
        <div class="profile-topics">
            <a href="#personal"><i class="fas fa-id-card"></i> Data Pribadi</a>
            <a href="#contact"><i class="fas fa-address-card"></i> Kontak & Alamat</a>
            <a href="#security"><i class="fas fa-lock"></i> Keamanan</a>
            <a href="#account-info"><i class="fas fa-info-circle"></i> Info Akun</a>
        </div>
        
        <?php if ($success): ?>
            <div class="success">
                <i class="fas fa-check-circle"></i> Profil berhasil diperbarui
            </div>
        <?php endif; ?>
        
        <?php if (!empty($error)): ?>
            <div class="error">
                <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
            </div>
        <?php endif; ?>
        
        <div class="profile-container">
            <div class="profile-sidebar">
                <div class="profile-menu">
                    <div class="profile-header">
                        <div class="profile-avatar">
                            <i class="fas fa-user"></i>
                        </div>
                        <div class="profile-name">
                            <?php echo $user['name']; ?>
                        </div>
                        <div class="profile-email">
                            <?php echo $user['email']; ?>
                        </div>
                    </div>  
                </div>
            </div>
            
            <div class="profile-content">
                <div class="profile-section">
                    <h2 id="personal"><i class="fas fa-user-edit"></i> Data Pribadi</h2>
                    <form action="profile.php" method="post" class="profile-form">
                        <div class="form-group">
                            <label for="name"><i class="fas fa-user"></i> Nama Lengkap:</label>
                            <input type="text" id="name" name="name" value="<?php echo $user['name']; ?>" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="email"><i class="fas fa-envelope"></i> Email:</label>
                            <input type="email" id="email" name="email" value="<?php echo $user['email']; ?>" required>
                        </div>
                        
                        <h3 id="contact" class="mt-2"><i class="fas fa-home"></i> Kontak & Alamat</h3>
                        <div class="form-group">
                            <label for="username"><i class="fas fa-user-tag"></i> Username:</label>
                            <input type="text" value="<?php echo $user['username']; ?>" disabled>
                            <small class="form-text">Username tidak dapat diubah</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="address"><i class="fas fa-map-marker-alt"></i> Alamat:</label>
                            <textarea id="address" name="address" placeholder="Masukkan alamat lengkap untuk pengiriman"><?php echo $user['address']; ?></textarea>
                        </div>
                        
                        <div class="form-group">
                            <label for="phone"><i class="fas fa-phone"></i> Nomor Telepon:</label>
                            <input type="text" id="phone" name="phone" value="<?php echo $user['phone']; ?>" placeholder="Contoh: 08123456789">
                        </div>
                        
                        <h3 id="security"><i class="fas fa-lock"></i> Ubah Password</h3>
                        <div class="form-group">
                            <label for="current_password">Password Saat Ini:</label>
                            <div class="password-input-wrapper">
                                <input type="password" id="current_password" name="current_password">
                                <span class="password-toggle" onclick="togglePassword('current_password')">
                                    <i class="far fa-eye" id="current_password-toggle-icon"></i>
                                </span>
                            </div>
                            <small class="form-text">Biarkan kosong jika tidak ingin mengubah password</small>
                        </div>
                        
                        <div class="form-group">
                            <label for="new_password">Password Baru:</label>
                            <div class="password-input-wrapper">
                                <input type="password" id="new_password" name="new_password">
                                <span class="password-toggle" onclick="togglePassword('new_password')">
                                    <i class="far fa-eye" id="new_password-toggle-icon"></i>
                                </span>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="confirm_password">Konfirmasi Password Baru:</label>
                            <div class="password-input-wrapper">
                                <input type="password" id="confirm_password" name="confirm_password">
                                <span class="password-toggle" onclick="togglePassword('confirm_password')">
                                    <i class="far fa-eye" id="confirm_password-toggle-icon"></i>
                                </span>
                            </div>
                        </div>
                        
                        <div class="form-actions">
                            <button type="submit" class="btn">
                                <i class="fas fa-save"></i> Simpan Perubahan
                            </button>
                        </div>
                    </form>
                </div>
                
                <div class="profile-section">
                    <h2 id="account-info"><i class="fas fa-info-circle"></i> Info Akun</h2>
                    <p>
                        <strong>Tanggal Bergabung:</strong> 
                        <?php echo date('d F Y', strtotime($user['created_at'])); ?>
                    </p>
                    <p>
                        <strong>Status Akun:</strong> 
                        <span class="badge badge-success">Aktif</span>
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

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