<?php
/**
 * actions/profile-save.php — POST handler: update own profile info
 * Both roles. POST only.
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/audit.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    redirect(base_url('pages/profile.php'));
}

require_login();
csrf_verify();

$user_id = current_user_id();
$name    = trim($_POST['name'] ?? '');
$email   = trim($_POST['email'] ?? '');

// ── Validation ────────────────────────────────────────────────────────────────

$errors = [];

if ($name === '') $errors[] = 'Full name is required.';
if ($email === '') $errors[] = 'Email is required.';
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Email is not valid.';

// Duplicate email check (exclude self)
if ($email !== '') {
    $dup = db()->prepare('SELECT id FROM users WHERE email = ? AND id != ?');
    $dup->execute([$email, $user_id]);
    if ($dup->fetch()) $errors[] = 'That email address is already used by another account.';
}

if ($errors) {
    set_flash('error', implode(' ', $errors));
    redirect(base_url('pages/profile.php'));
}

// ── Save ──────────────────────────────────────────────────────────────────────

$stmt = db()->prepare('UPDATE users SET name = ?, email = ? WHERE id = ?');
$stmt->execute([$name, $email, $user_id]);

// Update session name so the header reflects the change immediately
$_SESSION['name']  = $name;
$_SESSION['email'] = $email;

audit_log('user.profile_update', 'Updated own profile', $user_id, 'user');
set_flash('success', 'Profile updated successfully.');
redirect(base_url('pages/profile.php'));
