<?php
session_start();
$conn = new mysqli("localhost", "kkfxoaad", "Bitok@2025", "kkfxoaad_bella");

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userId = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $firstName = trim($_POST['firstName'] ?? '');
    $lastName  = trim($_POST['lastName'] ?? '');
    $email     = trim($_POST['email'] ?? '');
    $phone     = trim($_POST['phone'] ?? '');

    // Validate inputs
    $errors = [];
    if (!$firstName) $errors[] = "First name required.";
    if (!$lastName) $errors[] = "Last name required.";
    if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email required.";
    if (!$phone) $errors[] = "Phone required.";

    if ($errors) {
        $_SESSION['profile_errors'] = $errors;
        header("Location: edit-profile.php");
        exit();
    }

    // Update DB
    $stmt = $conn->prepare("UPDATE users SET firstName=?, lastName=?, email=?, phone=? WHERE id=?");
    $stmt->bind_param("ssssi", $firstName, $lastName, $email, $phone, $userId);
    $stmt->execute();
    $stmt->close();

    $_SESSION['name'] = $firstName . ' ' . $lastName;
    $conn->close();

    header("Location: profile.php");
    exit();
}

header("Location: edit-profile.php");
exit();
?>
