<?php
// 3CX Integration - Direct PHP search for customers and clients
header('Content-Type: application/json');

// Log access
$logFile = '/var/www/seraph3/storage/logs/3cx-search.log';
$logEntry = '[' . date('Y-m-d H:i:s') . '] Search accessed from IP: ' . $_SERVER['REMOTE_ADDR'];
file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

// Check for required parameters
if (!isset($_GET['number']) || empty($_GET['number'])) {
    http_response_code(400);
    echo json_encode([
        'success' => 'false',
        'message' => 'Phone number parameter is required'
    ]);
    exit;
}

if (!isset($_GET['api_key']) || empty($_GET['api_key'])) {
    http_response_code(200);
    echo json_encode([
        'success' => 'false',
        'message' => 'please provide API Key'
    ]);
    exit;
}

$number = $_GET['number'];
$apiKey = $_GET['api_key'];

// E.164 phone number normalization function
function normalizeToE164($phoneNumber, $defaultCountryCode = '1') {
    // Remove all non-numeric characters except +
    $cleaned = preg_replace('/[^0-9+]/', '', $phoneNumber);
    
    // If already starts with +, assume it's E.164 format
    if (strpos($cleaned, '+') === 0) {
        return $cleaned;
    }
    
    // If starts with country code (assuming US/Canada default)
    if (strlen($cleaned) === 11 && $cleaned[0] === '1') {
        return '+' . $cleaned;
    }
    
    // If 10 digits, add default country code
    if (strlen($cleaned) === 10) {
        return '+' . $defaultCountryCode . $cleaned;
    }
    
    // For other lengths, try to add default country code
    if (strlen($cleaned) >= 7) {
        return '+' . $defaultCountryCode . $cleaned;
    }
    
    // Return as-is with + prefix if too short
    return '+' . $cleaned;
}

$cleanNumber = preg_replace('/[^0-9+]/', '', $number);
$e164Number = normalizeToE164($number);

$logEntry = '[' . date('Y-m-d H:i:s') . '] Searching for number: ' . $number . ' (cleaned: ' . $cleanNumber . ', E.164: ' . $e164Number . ') - API key: ' . substr($apiKey, 0, 8) . '...' . PHP_EOL;
file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

try {
    // Database connection - read from Laravel's .env file
    $envFile = __DIR__ . '/../.env';
    $dbConfig = [];
    
    if (file_exists($envFile)) {
        $envContent = file_get_contents($envFile);
        $envLines = explode("\n", $envContent);
        
        foreach ($envLines as $line) {
            $line = trim($line);
            if (empty($line) || strpos($line, '#') === 0) continue;
            
            if (strpos($line, '=') !== false) {
                list($key, $value) = explode('=', $line, 2);
                $key = trim($key);
                $value = trim($value, '"\'');
                $dbConfig[$key] = $value;
            }
        }
    }
    
    // Database connection using Laravel's configuration
    $host = $dbConfig['DB_HOST'] ?? 'localhost';
    $dbname = $dbConfig['DB_DATABASE'] ?? 'seraph';
    $username = $dbConfig['DB_USERNAME'] ?? 'root';
    $password = $dbConfig['DB_PASSWORD'] ?? 'root';
    
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Validate API key
    try {
        $validApiKey = null;
        $stmt = $pdo->prepare("SELECT value FROM settings WHERE `key` = 'threecx_api_key' LIMIT 1");
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $validApiKey = $result ? $result['value'] : null;
        
        if (!$validApiKey || $apiKey !== $validApiKey) {
            $logEntry = '[' . date('Y-m-d H:i:s') . '] Invalid API key provided' . PHP_EOL;
            file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
            
            http_response_code(200);
            echo json_encode([
                'success' => 'false',
                'message' => 'Invalid API key provided'
            ]);
            exit;
        }
        
        $logEntry = '[' . date('Y-m-d H:i:s') . '] API key validated successfully' . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
    } catch (Exception $e) {
        // If settings table doesn't exist, deny access
        $logEntry = '[' . date('Y-m-d H:i:s') . '] API key validation failed - settings table issue: ' . $e->getMessage() . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        http_response_code(200);
        echo json_encode([
            'success' => 'false',
            'message' => 'Invalid API key provided'
        ]);
        exit;
    }
    
    // Search customers table first (direct phone columns)
    $logEntry = '[' . date('Y-m-d H:i:s') . '] Searching customers table for exact match' . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    
    $customersSql = "SELECT id, CONCAT(first_name, ' ', last_name) as name, email, 
                            COALESCE(phone, phone2, mobile) as phone
                     FROM customers 
                     WHERE (phone IN (?, ?) OR phone2 IN (?, ?) OR mobile IN (?, ?)) AND deleted_at IS NULL
                     LIMIT 1";
    $stmt = $pdo->prepare($customersSql);
    $stmt->execute([$cleanNumber, $e164Number, $cleanNumber, $e164Number, $cleanNumber, $e164Number]);
    $customerMatch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($customerMatch) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] Found customer match: ' . $customerMatch['name'] . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        echo json_encode([
            'success' => 'true',
            'id' => $customerMatch['id'],
            'name' => $customerMatch['name'],
            'company' => '',
            'phone' => $customerMatch['phone'],
            'email' => $customerMatch['email'] ?: '',
            'match_type' => 'exact',
            'source' => 'customer'
        ]);
        exit;
    }
    
    // Search clients through site_users (primary_contact relationship)
    $logEntry = '[' . date('Y-m-d H:i:s') . '] Searching clients table via site_users for exact match' . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    
    $clientsSql = "SELECT c.id, c.name, su.email, 
                          COALESCE(su.phone, su.mobile) as phone
                   FROM clients c 
                   JOIN site_users su ON c.primary_contact = su.id
                   WHERE (su.phone IN (?, ?) OR su.mobile IN (?, ?)) AND c.deleted_at IS NULL
                   LIMIT 1";
    $stmt = $pdo->prepare($clientsSql);
    $stmt->execute([$cleanNumber, $e164Number, $cleanNumber, $e164Number]);
    $clientMatch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($clientMatch) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] Found client match: ' . $clientMatch['name'] . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        echo json_encode([
            'success' => 'true',
            'id' => $clientMatch['id'],
            'name' => $clientMatch['name'],
            'company' => $clientMatch['name'],
            'phone' => $clientMatch['phone'],
            'email' => $clientMatch['email'] ?: '',
            'match_type' => 'exact',
            'source' => 'client'
        ]);
        exit;
    }
    
    // If no exact match, try partial matches
    $logEntry = '[' . date('Y-m-d H:i:s') . '] No exact match found, trying partial matches' . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    
    $searchPattern = "%$cleanNumber%";
    $e164SearchPattern = "%$e164Number%";
    
    // Search customers with partial match
    $customersLikeSql = "SELECT id, CONCAT(first_name, ' ', last_name) as name, email, 
                                COALESCE(phone, phone2, mobile) as phone
                         FROM customers 
                         WHERE (phone LIKE ? OR phone2 LIKE ? OR mobile LIKE ? OR 
                                phone LIKE ? OR phone2 LIKE ? OR mobile LIKE ?) AND deleted_at IS NULL
                         LIMIT 1";
    $stmt = $pdo->prepare($customersLikeSql);
    $stmt->execute([$searchPattern, $searchPattern, $searchPattern, $e164SearchPattern, $e164SearchPattern, $e164SearchPattern]);
    $customerPartialMatch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($customerPartialMatch) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] Found customer partial match: ' . $customerPartialMatch['name'] . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        echo json_encode([
            'success' => 'true',
            'id' => $customerPartialMatch['id'],
            'name' => $customerPartialMatch['name'],
            'company' => '',
            'phone' => $customerPartialMatch['phone'],
            'email' => $customerPartialMatch['email'] ?: '',
            'match_type' => 'partial',
            'source' => 'customer'
        ]);
        exit;
    }
    
    // Search clients with partial match
    $clientsLikeSql = "SELECT c.id, c.name, su.email, 
                              COALESCE(su.phone, su.mobile) as phone
                       FROM clients c 
                       JOIN site_users su ON c.primary_contact = su.id
                       WHERE (su.phone LIKE ? OR su.mobile LIKE ? OR 
                              su.phone LIKE ? OR su.mobile LIKE ?) AND c.deleted_at IS NULL
                       LIMIT 1";
    $stmt = $pdo->prepare($clientsLikeSql);
    $stmt->execute([$searchPattern, $searchPattern, $e164SearchPattern, $e164SearchPattern]);
    $clientPartialMatch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($clientPartialMatch) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] Found client partial match: ' . $clientPartialMatch['name'] . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        echo json_encode([
            'success' => 'true',
            'id' => $clientPartialMatch['id'],
            'name' => $clientPartialMatch['name'],
            'company' => $clientPartialMatch['name'],
            'phone' => $clientPartialMatch['phone'],
            'email' => $clientPartialMatch['email'] ?: '',
            'match_type' => 'partial',
            'source' => 'client'
        ]);
        exit;
    }
    
    // No match found
    $logEntry = '[' . date('Y-m-d H:i:s') . '] No matches found for number: ' . $cleanNumber . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    
    http_response_code(200);
    echo json_encode([
        'success' => false,
        'message' => 'No matching contact found',        
    ]);
    
} catch (Exception $e) {
    $logEntry = '[' . date('Y-m-d H:i:s') . '] ERROR: ' . $e->getMessage() . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Search error: ' . $e->getMessage()
    ]);
}
?>