<?php
// complete-profile.php — Backend handler for profile-setup.php
//
// Final step of the email signup flow. By the time this runs:
//   1. signup-email.php  -> send-otp.php   issued a code for the email
//   2. verify-email.php  -> verify-otp.php confirmed the code and set
//                            $_SESSION['signup_email'] / 'signup_email_verified'
//
// This handler trusts $_SESSION['signup_email'] (not the posted hidden
// field) as the source of truth for which email was verified, creates the
// customer account, logs the user in, and redirects to dashboard.php.
//
// Integration note: inserting a row into `users` with role='customer'
// triggers `trg_after_customer_insert`, which creates the matching
// `wallets` row (Personal Wallet + Meal Ticket balances) — no wallet
// creation logic is duplicated here.

session_start();
require_once __DIR__ . '/config/db.php';

function back_to_profile_setup(string $error): void
{
    $_SESSION['profile_error'] = $error;
    header('Location: profile-setup.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: profile-setup.php');
    exit;
}

// --- The verified email must come from the session, not the form ---
$email = $_SESSION['signup_email'] ?? '';
if ($email === '' || empty($_SESSION['signup_email_verified']) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header('Location: signup-email.php');
    exit;
}

$fullName = trim($_POST['full_name'] ?? '');
$phone    = trim($_POST['phone'] ?? '');
$password = (string) ($_POST['password'] ?? '');

if ($fullName === '' || $phone === '' || $password === '') {
    back_to_profile_setup('Please fill in all fields.');
}

if (strlen($password) < 8) {
    back_to_profile_setup('Password must be at least 8 characters.');
}

if (!preg_match('/^\+?[0-9\s-]{7,20}$/', $phone)) {
    back_to_profile_setup('Please enter a valid phone number.');
}

try {
    // Re-check for race conditions: email or phone registered since OTP step.
    $chk = $conn->prepare('SELECT id FROM users WHERE email = ? OR phone = ? LIMIT 1');
    $chk->bind_param('ss', $email, $phone);
    $chk->execute();
    $chk->store_result();

    if ($chk->num_rows > 0) {
        back_to_profile_setup('An account with this email or phone number already exists.');
    }

    $passwordHash = password_hash($password, PASSWORD_DEFAULT);

    $ins = $conn->prepare(
        "INSERT INTO users (name, email, phone, password, role, status, created_at)
         VALUES (?, ?, ?, ?, 'customer', 1, NOW())"
    );
    $ins->bind_param('ssss', $fullName, $email, $phone, $passwordHash);

    if (!$ins->execute()) {
        back_to_profile_setup('Could not create your account. Please try again.');
    }

    $newUserId = (int) $conn->insert_id;

    // --- Auto sign-in ---
    session_regenerate_id(true);
    $_SESSION['user_id']    = $newUserId;
    $_SESSION['user_name']  = $fullName;
    $_SESSION['user_email'] = $email;
    $_SESSION['role']       = 'customer';

    // Clean up signup-flow session state.
    unset($_SESSION['signup_email'], $_SESSION['signup_email_verified'], $_SESSION['profile_error']);

    // Returning-user cookie: lets splash.php skip the onboarding screens
    // (welcome/order/manage) and send the user straight to signin.php next time.
    setcookie('dabil_returning', '1', [
        'expires'  => time() + 60 * 60 * 24 * 365,
        'path'     => '/',
        'secure'   => !empty($_SERVER['HTTPS']),
        'httponly' => true,
        'samesite' => 'Lax',
    ]);

    header('Location: dashboard.php');
    exit;

} catch (mysqli_sql_exception $e) {
    back_to_profile_setup('Something went wrong. Please try again.');
}
