
<?php
// includes/customer_bridge_helper.php
// Connect manual tickets to a CX customer account by email so chat rooms can be created.

function splitFullNameForCustomer(string $fullName): array {
    $fullName = trim(preg_replace('/\s+/', ' ', $fullName));
    if ($fullName === '') return ['Customer', ''];
    $parts = explode(' ', $fullName);
    if (count($parts) === 1) return [$parts[0], ''];
    $last = array_pop($parts);
    return [trim(implode(' ', $parts)) ?: 'Customer', $last];
}

function findOrCreateCustomerByEmail(PDO $db, string $email, string $fullName, string $phone = '', string $address = '', ?int $cityId = null, string $state = '', string $zip = ''): ?int {
    $email = strtolower(trim($email));
    if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) return null;

    $stmt = $db->prepare("SELECT id FROM customers WHERE LOWER(email) = LOWER(:email) LIMIT 1");
    $stmt->execute([':email' => $email]);
    $existing = $stmt->fetchColumn();
    if ($existing) return (int)$existing;

    [$first, $last] = splitFullNameForCustomer($fullName);
    $tempPassword = password_hash(bin2hex(random_bytes(12)), PASSWORD_DEFAULT);
    $token = bin2hex(random_bytes(32));

    $stmt = $db->prepare("INSERT INTO customers (
            first_name, last_name, email, phone_number, password, address, city_id, state, zip_code,
            is_active, email_verified, verification_token
        ) VALUES (
            :first_name, :last_name, :email, :phone, :password, :address, :city_id, :state, :zip,
            1, 0, :token
        )");
    $stmt->execute([
        ':first_name' => $first,
        ':last_name' => $last,
        ':email' => $email,
        ':phone' => $phone,
        ':password' => $tempPassword,
        ':address' => $address,
        ':city_id' => $cityId,
        ':state' => $state,
        ':zip' => $zip,
        ':token' => $token,
    ]);
    return (int)$db->lastInsertId();
}

function attachTicketToCustomerAndChat(PDO $db, int $requestId, ?int $customerId): bool {
    if (!$customerId || $requestId <= 0) return false;
    $stmt = $db->prepare("UPDATE service_requests SET customer_id = :customer_id WHERE id = :request_id");
    $stmt->execute([':customer_id' => $customerId, ':request_id' => $requestId]);

    if (function_exists('getOrCreateConversation')) {
        return (bool)getOrCreateConversation($db, $requestId, null);
    }
    return true;
}
