<?php
require_once __DIR__ . '/../db.php';
session_start();

header('Content-Type: application/json');

// Log raw POST data for debugging
file_put_contents(__DIR__ . "/debug_log.txt", print_r($_POST, true) . PHP_EOL, FILE_APPEND);
file_put_contents("debug_completeSignup.txt", print_r($_POST, true) . PHP_EOL, FILE_APPEND);
file_put_contents("debug_log.txt", print_r($_POST, true) . PHP_EOL, FILE_APPEND);

// Capture input data
$user_id = $_POST['user_id'] ?? '';
$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$email = trim($_POST['email'] ?? '');

// ✅ Log received data for debugging
file_put_contents(__DIR__ . "/debug_log.txt", "Received Data: " . print_r($_POST, true) . PHP_EOL, FILE_APPEND);




// ✅ Step 1: Ensure all fields exist
if (!$user_id || !$first_name || !$last_name || !$email) {
    echo json_encode(["success" => false, "message" => "All fields are required."]);
    exit;
}

// ✅ Step 2: Check if user exists
$stmt = $pdo->prepare("SELECT * FROM users WHERE user_id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    echo json_encode(["success" => false, "message" => "User not found in database."]);
    exit;
}

// ✅ Step 3: Update the user's data
try {
    $stmt = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ? WHERE user_id = ?");
    $stmt->execute([$first_name, $last_name, $email, $user_id]);

    file_put_contents("debug_log.txt", "✅ SUCCESS: Updated user $user_id\n", FILE_APPEND);
} catch (PDOException $e) {
    file_put_contents("debug_log.txt", "❌ ERROR: " . $e->getMessage() . "\n", FILE_APPEND);
}


// ✅ Step 4: Check if the update was successful
// ✅ FORCE SAVE USER INFO
$stmt = $pdo->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ? WHERE user_id = ?");
$success = $stmt->execute([$first_name, $last_name, $email, $user_id]);

if ($success) {
    echo json_encode(["success" => true, "redirect" => "user-dashboard.php"]);
} else {
    echo json_encode(["success" => false, "message" => "Database update failed."]);
}
exit;

// ✅ Step 5: Log the user in using the correct session variable
$_SESSION['logged_in_user'] = $user_id;

// ✅ Step 6: Confirm success and redirect
echo json_encode(["success" => true, "redirect" => "user-dashboard.php"]);
exit;
