<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();
requireLogin();

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    header('Location: logout.php');
    exit;
}

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'change_password') {
    $current = $_POST['current_password'] ?? '';
    $new = $_POST['new_password'] ?? '';
    $confirm = $_POST['confirm_password'] ?? '';

    if (!$current || !$new || !$confirm) {
        $message = 'Please fill in all password fields.';
        $messageType = 'error';
    } elseif (!password_verify($current, $user['password_hash'])) {
        $message = 'Current password is incorrect.';
        $messageType = 'error';
    } elseif (strlen($new) < 6) {
        $message = 'New password must be at least 6 characters.';
        $messageType = 'error';
    } elseif ($new !== $confirm) {
        $message = 'New passwords do not match.';
        $messageType = 'error';
    } else {
        $user['password_hash'] = password_hash($new, PASSWORD_DEFAULT);
        saveUser($user);
        $message = 'Password updated successfully!';
        $messageType = 'success';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'upload_avatar') {
    if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
        $message = 'Please choose an image to upload.';
        $messageType = 'error';
    } else {
        $file = $_FILES['avatar'];
        $allowed = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp'];
        $mime = mime_content_type($file['tmp_name']);

        if (!isset($allowed[$mime])) {
            $message = 'Only PNG, JPG, GIF or WEBP images are allowed.';
            $messageType = 'error';
        } elseif ($file['size'] > 1.5 * 1024 * 1024) {
            $message = 'Image must be smaller than 1.5MB.';
            $messageType = 'error';
        } else {
            $imgData = file_get_contents($file['tmp_name']);
            $dataUri = 'data:' . $mime . ';base64,' . base64_encode($imgData);
            $user['avatar'] = $dataUri;
            saveUser($user);
            $message = 'Avatar updated!';
            $messageType = 'success';
        }
    }
}

$pageTitle = 'Profile';
$activeNav = 'profile';
include __DIR__ . '/includes/user_header.php';
?>

<div class="page-head">
  <h1 class="page-title">Profile</h1>
  <p class="page-sub">Manage your avatar and account password.</p>
</div>

<?php if ($message): ?>
  <div class="alert alert-<?= $messageType === 'success' ? 'ok' : 'warn' ?>"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="card">
  <h2 class="card-title">Profile picture</h2>
  <div class="card-sub">Upload a logo or photo for your account. Shown in the admin panel too.</div>

  <div class="flex items-center" style="gap:20px; flex-wrap:wrap; margin-top:16px;">
    <?php if (!empty($user['avatar'])): ?>
      <img src="<?= htmlspecialchars($user['avatar']) ?>" alt="Avatar" style="width:84px; height:84px; border-radius:50%; object-fit:cover; border:2px solid var(--primary);">
    <?php else: ?>
      <div style="width:84px; height:84px; border-radius:50%; background:var(--surface-hover); display:flex; align-items:center; justify-content:center; font-size:34px; color:var(--muted); border:2px dashed var(--border);">
        <?= mb_substr(htmlspecialchars($user['name']), 0, 1) ?>
      </div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data" style="flex:1; min-width:200px;">
      <input type="hidden" name="action" value="upload_avatar">
      <input class="input" type="file" name="avatar" accept="image/png,image/jpeg,image/gif,image/webp" required>
      <button type="submit" class="btn btn-primary" style="margin-top:10px;">Upload new avatar</button>
    </form>
  </div>
</div>

<div class="card">
  <h2 class="card-title">Change password</h2>
  <div class="card-sub">Update your account login password.</div>

  <form method="POST" style="margin-top:16px;">
    <input type="hidden" name="action" value="change_password">

    <label class="label" for="curPass">Current password</label>
    <input class="input" type="password" id="curPass" name="current_password" placeholder="Enter current password" required>

    <label class="label" for="newPass">New password</label>
    <input class="input" type="password" id="newPass" name="new_password" placeholder="At least 6 characters" required>

    <label class="label" for="confPass">Confirm new password</label>
    <input class="input" type="password" id="confPass" name="confirm_password" placeholder="Re-enter new password" required>

    <div class="row mt-24">
      <button type="submit" class="btn btn-primary">Update password</button>
    </div>
  </form>
</div>

<?php include __DIR__ . '/includes/user_footer.php'; ?>
