<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");  
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();	

$search = $_POST['search'] ?? '';

// Assuming $DB is defined in mydb.php or session.php
// If $DB is not defined, define it explicitly
if (!isset($DB)) {
    $DB = 'chandj'; // Replace with your actual database name
}

try {
    // Construct SQL query to search in output table based on search term
    $sql = "SELECT phone, outputplace, receiver FROM {$DB}.output WHERE 
            receiver LIKE :search ";
    
    $stmh = $pdo->prepare($sql);
    $searchTerm = '%' . $search . '%';
    $stmh->bindParam(':search', $searchTerm, PDO::PARAM_STR);
    $stmh->execute();
    $output_rows = $stmh->fetchAll(PDO::FETCH_ASSOC);

    // Function to normalize strings: remove spaces, special characters and convert to lowercase
    function normalize($str) {
        return strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $str));
    }

    // Remove duplicate rows based on 'phone', 'outputplace', 'receiver' columns
    $unique_rows = [];
    $seen = [];
    foreach ($output_rows as $row) { 
        $normalized_phone = normalize($row['phone']);
        $normalized_outputplace = normalize($row['outputplace']);
        $normalized_receiver = normalize($row['receiver']);
        $key = $normalized_phone . '|' . $normalized_outputplace . '|' . $normalized_receiver;
        if (!isset($seen[$key])) {
            $unique_rows[] = $row;
            $seen[$key] = true;
        }
    }

    // Output the results as JSON
    header('Content-Type: application/json');
    echo json_encode($unique_rows);

} catch (PDOException $Exception) {
    // Output the error message as JSON
    header('Content-Type: application/json');
    echo json_encode(["error" => $Exception->getMessage()]);
    exit;
}
?>
