<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
$user = hw_auth_user();
if (!$user) hw_json(['message' => 'Unauthorized'], 401);

$input = hw_input_json();
$firstName = hw_sanitize_string($input['first_name'] ?? '');
$lastName = hw_sanitize_string($input['last_name'] ?? '');
$email = hw_sanitize_string($input['email'] ?? '');
$password = (string)($input['password'] ?? '');

if (!$firstName || !$lastName) hw_json(['message' => 'First and last name are required'], 422);
if (!hw_validate_email($email)) hw_json(['message' => 'Valid email is required'], 422);

try {
    $pdo = hw_db();
    
    // Check if email is already taken by another user
    $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? AND id != ? LIMIT 1');
    $stmt->execute([$email, $user['sub']]);
    if ($stmt->fetch()) hw_json(['message' => 'Email already in use'], 409);
    
    // Update user info
    if ($password) {
        if (strlen($password) < 6) hw_json(['message' => 'Password must be at least 6 characters'], 422);
        $stmt = $pdo->prepare('UPDATE users SET first_name = ?, last_name = ?, email = ?, password_hash = ? WHERE id = ?');
        $stmt->execute([$firstName, $lastName, $email, hw_hash_password($password), $user['sub']]);
    } else {
        $stmt = $pdo->prepare('UPDATE users SET first_name = ?, last_name = ?, email = ? WHERE id = ?');
        $stmt->execute([$firstName, $lastName, $email, $user['sub']]);
    }
    
    // Audit log
    $stmt = $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("email", ?))');
    $stmt->execute([$user['sub'], 'profile_updated', $email]);
    
    hw_json(['message' => 'Profile updated successfully']);
} catch (Throwable $e) {
    hw_json(['message' => 'Server error', 'error' => $e->getMessage()], 500);
}
?>