<?php
// ==========================
// edit_profile.php - DemoBank
// ==========================

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';

if (session_status() === PHP_SESSION_NONE) session_start();

// Ensure user is logged in
$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    header("Location: /auth/login.php");
    exit;
}

// Database connection
$conn = db();
if (!$conn) die("Database connection failed");

// Fetch user info
$stmt = $conn->prepare("SELECT * FROM users WHERE id=?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Currency symbol map (for display consistency)
$currencySymbols = [
    'USD' => '$',
    'EUR' => '€',
    'GBP' => '£',
    'JPY' => '¥',
    'CNY' => '¥',
    'NGN' => '₦',
    'GHS' => '₵',
    'INR' => '₹',
    'CAD' => 'C$',
    'AUD' => 'A$'
];

$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // ---------------------------
    // Handle password change
    // ---------------------------
    $current_password = trim($_POST['current_password'] ?? '');
    $new_password = trim($_POST['password'] ?? '');
    $confirm_password = trim($_POST['confirm_password'] ?? '');

    if ($new_password || $confirm_password) {
        if (!$current_password) {
            $message = "Please enter your current password to change it.";
            $message_type = "error";
        } else {
            $stmt = $conn->prepare("SELECT password FROM users WHERE id=?");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $stmt->bind_result($hashed_password_db);
            $stmt->fetch();
            $stmt->close();

            if (!password_verify($current_password, $hashed_password_db)) {
                $message = "Current password is incorrect.";
                $message_type = "error";
            } elseif ($new_password !== $confirm_password) {
                $message = "New passwords do not match.";
                $message_type = "error";
            } elseif (strlen($new_password) < 6) {
                $message = "New password must be at least 6 characters.";
                $message_type = "error";
            } else {
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt = $conn->prepare("UPDATE users SET password=? WHERE id=?");
                $stmt->bind_param("si", $hashed_password, $user_id);
                $stmt->execute();
                $stmt->close();

                $message = "Password updated successfully.";
                $message_type = "success";
            }
        }
    }

    // ---------------------------
    // Handle profile photo upload
    // ---------------------------
    if (!empty($_FILES['profile_photo']['name'])) {
        $allowed = ['jpg','jpeg','png','gif'];
        $ext = strtolower(pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION));

        if (!in_array($ext, $allowed)) {
            $message = "Invalid file type for profile photo.";
            $message_type = "error";
        } else {
            $target_dir = __DIR__ . "/../uploads/profile_photos/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0755, true);

            $new_filename = "user_" . $user_id . "_" . time() . "." . $ext;
            $target_file = $target_dir . $new_filename;

            if (!move_uploaded_file($_FILES['profile_photo']['tmp_name'], $target_file)) {
                $message = "Failed to upload profile photo.";
                $message_type = "error";
            } else {
                $profile_photo_path = "/uploads/profile_photos/" . $new_filename;
                $stmt = $conn->prepare("UPDATE users SET profile_photo=? WHERE id=?");
                $stmt->bind_param("si", $profile_photo_path, $user_id);
                $stmt->execute();
                $stmt->close();

                $message = "Profile photo updated successfully.";
                $message_type = "success";
                $user['profile_photo'] = $profile_photo_path; // Update immediately
            }
        }
    }
}

// ---------------------------
// Capture content for layout
// ---------------------------
ob_start();
?>

<h1>Edit Profile</h1>

<?php if($message): ?>
    <div style="margin-bottom:20px;padding:10px;border-radius:5px;color:white;background:<?= $message_type==='success'?'#28a745':'#dc3545' ?>;">
        <?= htmlspecialchars($message) ?>
    </div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data" style="max-width:500px;background:#fff;padding:20px;border-radius:8px;box-shadow:0 2px 5px rgba(0,0,0,0.1);">

    <label>Current Password *</label>
    <input type="password" name="current_password" placeholder="Enter current password" style="width:100%;padding:8px;margin-bottom:10px;">

    <label>New Password</label>
    <input type="password" name="password" placeholder="Enter new password" style="width:100%;padding:8px;margin-bottom:10px;">

    <label>Confirm New Password</label>
    <input type="password" name="confirm_password" placeholder="Confirm new password" style="width:100%;padding:8px;margin-bottom:10px;">

    <label>Profile Photo</label>
    <input type="file" name="profile_photo" accept="image/*" style="margin-bottom:10px;">
    <?php if (!empty($user['profile_photo'])): ?>
        <div style="margin-bottom:10px;">
            <img src="<?= $user['profile_photo'] ?>" alt="Profile Photo" style="width:100px;height:100px;border-radius:8px;">
        </div>
    <?php endif; ?>

    <button type="submit" style="background:#1a73e8;color:white;padding:10px 20px;border:none;border-radius:5px;cursor:pointer;">Update</button>

</form>

<?php
$content = ob_get_clean();

// Render layout
renderLayout("Edit Profile", $content, $conn);