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

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized Access']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

$userId = $_SESSION['user_id'];
$firstName = trim($_POST['first_name'] ?? '');
$middleName = trim($_POST['middle_name'] ?? '');
$lastName = trim($_POST['last_name'] ?? '');
$extension = trim($_POST['extension'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone_number'] ?? '');
$position = trim($_POST['position'] ?? '');
$newUsername = trim($_POST['new_username'] ?? '');
$newPassword = $_POST['new_password'] ?? '';
$confirmPassword = $_POST['confirm_password'] ?? '';

if (empty($firstName) || empty($lastName) || empty($email) || empty($phone) || empty($position) || empty($newUsername) || empty($newPassword)) {
    echo json_encode(['success' => false, 'message' => 'All required fields must be filled.']);
    exit;
}

if ($newPassword !== $confirmPassword) {
    echo json_encode(['success' => false, 'message' => 'Passwords do not match.']);
    exit;
}

if (strlen($newPassword) < 8) {
    echo json_encode(['success' => false, 'message' => 'Password must be at least 8 characters long.']);
    exit;
}

// Email format validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Please enter a valid email address.']);
    exit;
}

// PH Phone validation (11 digits, starts with 09)
if (!preg_match('/^09\d{9}$/', $phone)) {
    echo json_encode(['success' => false, 'message' => 'Please enter a valid 11-digit Philippine mobile number starting with 09.']);
    exit;
}

try {
    // 1. Check if email is taken by another user
    $stmtEmail = $pdo->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
    $stmtEmail->execute([$email, $userId]);
    if ($stmtEmail->fetch()) {
        echo json_encode(['success' => false, 'message' => 'This email address is already in use by another account.']);
        exit;
    }

    // 2. Check if username is taken by another user
    $stmtUser = $pdo->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
    $stmtUser->execute([$newUsername, $userId]);
    if ($stmtUser->fetch()) {
        echo json_encode(['success' => false, 'message' => 'This username is already taken.']);
        exit;
    }

    // 3. Check if phone number is taken by another user
    $stmtPhone = $pdo->prepare("SELECT id FROM users WHERE phone_number = ? AND id != ?");
    $stmtPhone->execute([$phone, $userId]);
    if ($stmtPhone->fetch()) {
        echo json_encode(['success' => false, 'message' => 'This mobile number is already registered to another account.']);
        exit;
    }

    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

    // 3. Update user profile
    $stmtUpdate = $pdo->prepare("
        UPDATE users SET 
            first_name = ?, 
            middle_name = ?, 
            last_name = ?, 
            extension = ?, 
            email = ?, 
            phone_number = ?, 
            position = ?, 
            username = ?,
            password = ?,
            is_first_login = 0 
        WHERE id = ?
    ");

    $stmtUpdate->execute([
        $firstName,
        $middleName,
        $lastName,
        $extension,
        $email,
        $phone,
        $position,
        $newUsername,
        $hashedPassword,
        $userId
    ]);

    // 3. Update Session Info
    $_SESSION['name'] = $firstName;
    $_SESSION['is_first_login'] = 0;

    echo json_encode(['success' => true, 'message' => 'Welcome! Your profile has been successfully completed.']);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
