<?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';
$clientIP = $_SERVER['REMOTE_ADDR'];
$requestUri = $_SERVER['REQUEST_URI'] ?? 'N/A';
$fullUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'N/A') . $requestUri;

$logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | START SEARCH' . PHP_EOL;
$logEntry .= '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | FULL URL: ' . $fullUrl . PHP_EOL;
file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

// Check for required parameters
if (!isset($_GET['number']) || empty($_GET['number'])) {
    $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | ERROR: Missing number parameter' . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

    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'])) {
    $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | ERROR: Missing API key' . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

    http_response_code(200);
    echo json_encode([
        'success' => 'false',
        'message' => 'please provide API Key'
    ]);
    exit;
}

$number = $_GET['number'];
$apiKey = $_GET['api_key'];
$cleanNumber = preg_replace('/[^0-9+]/', '', $number);

$logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | RAW NUMBER: ' . $number . ' | CLEANED: ' . $cleanNumber . ' | API: ' . 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';
    $appUrl = rtrim($dbConfig['APP_URL'] ?? 'https://localhost:8000', '/');
    
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Helper function to generate consistent response
    function generateResponse($data, $matchType, $source, $appUrl, $cleanNumber) {
        // Determine phone and number fields based on what was matched
        $matchedPhone = '';
        $matchedNumber = '';

        // Determine matched numbers based on source and match type
        if ($matchType === 'exact') {
            if ($data['mobile'] === $cleanNumber) {
                $matchedNumber = $data['mobile'];
                $matchedPhone = $source === 'customer' ? ($data['phone'] ?: $data['phone2']) : $data['phone'];
            } elseif ($data['phone'] === $cleanNumber || ($source === 'customer' && $data['phone2'] === $cleanNumber)) {
                $matchedPhone = $source === 'customer' ? ($data['phone'] ?: $data['phone2']) : $data['phone'];
                $matchedNumber = $data['mobile'];
            }
        } else {
            // Partial match - check which field contains the number (including right-side matches)
            if ($data['mobile'] && (strpos($data['mobile'], $cleanNumber) !== false || substr($data['mobile'], -strlen($cleanNumber)) === $cleanNumber)) {
                $matchedNumber = $data['mobile'];
                $matchedPhone = $source === 'customer' ? ($data['phone'] ?: $data['phone2']) : $data['phone'];
            } elseif ($data['phone'] && (strpos($data['phone'], $cleanNumber) !== false || substr($data['phone'], -strlen($cleanNumber)) === $cleanNumber)) {
                $matchedPhone = $data['phone'];
                $matchedNumber = $data['mobile'];
            } elseif ($source === 'customer' && $data['phone2'] && (strpos($data['phone2'], $cleanNumber) !== false || substr($data['phone2'], -strlen($cleanNumber)) === $cleanNumber)) {
                $matchedPhone = $data['phone2'];
                $matchedNumber = $data['mobile'];
            }

            // Fallback: if still empty, just use whatever is available
            if (!$matchedPhone && !$matchedNumber) {
                $matchedPhone = $source === 'customer' ? ($data['phone'] ?: $data['phone2']) : $data['phone'];
                $matchedNumber = $data['mobile'];
            }
        }
        
        // Determine name, firstname, lastname, and company based on source
        if ($source === 'customer') {
            $name = trim($data['first_name'] . ' ' . $data['last_name']);
            $firstname = $data['first_name'];
            $lastname = $data['last_name'];
            $company = null;
        } else {
            $name = $data['name'];
            $company = $data['name'];
            
            // Split name by space if only name is available
            $nameParts = explode(' ', trim($data['name']), 2);
            $firstname = $nameParts[0] ?? '';
            $lastname = $nameParts[1] ?? '';
        }
        
        return [
            'success' => 'true',
            'id' => $data['id'],
            'name' => $name,
            'firstname' => $firstname,
            'lastname' => $lastname,
            'company' => $company,
            'phone' => $matchedPhone ?: '',
            'number' => $matchedNumber ?: '',
            'email' => $data['email'] ?: '',
            'match_type' => $matchType,
            'source' => $source,            
            'url' => $appUrl . '/clients#/customer/' . $data['id']
        ];
    }
    
    // Helper function to log and return response
    function logAndReturnResponse($response, $logFile, $clientIP) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | SUCCESS | phone:' . ($response['phone'] ?: 'none') . ' | number:' . ($response['number'] ?: 'none') . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        $logEntry = str_repeat('-', 80) . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        echo json_encode($response);
        exit;
    }
    
    // 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') . '] IP: ' . $clientIP . ' | ERROR: Invalid API key' . 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') . '] IP: ' . $clientIP . ' | API: Valid' . 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') . '] IP: ' . $clientIP . ' | ERROR: API validation failed' . 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') . '] IP: ' . $clientIP . ' | SEARCH: customers exact' . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

    // Try exact match first
    $customersSql = "SELECT id, first_name, last_name, email, phone, phone2, mobile
                     FROM customers
                     WHERE (phone = ? OR phone2 = ? OR mobile = ?) AND deleted_at IS NULL
                     LIMIT 1";
    $stmt = $pdo->prepare($customersSql);
    $stmt->execute([$cleanNumber, $cleanNumber, $cleanNumber]);
    $customerMatch = $stmt->fetch(PDO::FETCH_ASSOC);

    // If no exact match and number is less than 10 digits, try right-side match
    if (!$customerMatch && strlen($cleanNumber) < 10) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | SEARCH: customers right-match (truncated number)' . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

        $numDigits = strlen($cleanNumber);
        $customersSql = "SELECT id, first_name, last_name, email, phone, phone2, mobile
                         FROM customers
                         WHERE (RIGHT(phone, ?) = ? OR RIGHT(phone2, ?) = ? OR RIGHT(mobile, ?) = ?)
                         AND deleted_at IS NULL
                         LIMIT 1";
        $stmt = $pdo->prepare($customersSql);
        $stmt->execute([$numDigits, $cleanNumber, $numDigits, $cleanNumber, $numDigits, $cleanNumber]);
        $customerMatch = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    if ($customerMatch) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | MATCH: customer #' . $customerMatch['id'] . ' ' . $customerMatch['first_name'] . ' ' . $customerMatch['last_name'] . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        $response = generateResponse($customerMatch, 'exact', 'customer', $appUrl, $cleanNumber);
        logAndReturnResponse($response, $logFile, $clientIP);
    }
    
    // Search clients through site_users (primary_contact relationship)
    $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | SEARCH: clients exact' . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

    // Try exact match first
    $clientsSql = "SELECT c.id, c.name, su.email, su.phone, su.mobile
                   FROM clients c
                   JOIN site_users su ON c.primary_contact = su.id
                   WHERE (su.phone = ? OR su.mobile = ?) AND c.deleted_at IS NULL
                   LIMIT 1";
    $stmt = $pdo->prepare($clientsSql);
    $stmt->execute([$cleanNumber, $cleanNumber]);
    $clientMatch = $stmt->fetch(PDO::FETCH_ASSOC);

    // If no exact match and number is less than 10 digits, try right-side match
    if (!$clientMatch && strlen($cleanNumber) < 10) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | SEARCH: clients right-match (truncated number)' . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);

        $numDigits = strlen($cleanNumber);
        $clientsSql = "SELECT c.id, c.name, su.email, su.phone, su.mobile
                       FROM clients c
                       JOIN site_users su ON c.primary_contact = su.id
                       WHERE (RIGHT(su.phone, ?) = ? OR RIGHT(su.mobile, ?) = ?)
                       AND c.deleted_at IS NULL
                       LIMIT 1";
        $stmt = $pdo->prepare($clientsSql);
        $stmt->execute([$numDigits, $cleanNumber, $numDigits, $cleanNumber]);
        $clientMatch = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    if ($clientMatch) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | MATCH: client #' . $clientMatch['id'] . ' ' . $clientMatch['name'] . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        $response = generateResponse($clientMatch, 'exact', 'client', $appUrl, $cleanNumber);
        logAndReturnResponse($response, $logFile, $clientIP);
    }
    
    // If no exact match, try partial matches
    $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | SEARCH: partial matches' . PHP_EOL;
    file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
    
    $searchPattern = "%$cleanNumber%";
    
    // Search customers with partial match
    $customersLikeSql = "SELECT id, first_name, last_name, email, phone, phone2, mobile
                         FROM customers 
                         WHERE (phone LIKE ? OR phone2 LIKE ? OR mobile LIKE ?) AND deleted_at IS NULL
                         LIMIT 1";
    $stmt = $pdo->prepare($customersLikeSql);
    $stmt->execute([$searchPattern, $searchPattern, $searchPattern]);
    $customerPartialMatch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($customerPartialMatch) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | PARTIAL: customer #' . $customerPartialMatch['id'] . ' ' . $customerPartialMatch['first_name'] . ' ' . $customerPartialMatch['last_name'] . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        $response = generateResponse($customerPartialMatch, 'partial', 'customer', $appUrl, $cleanNumber);
        logAndReturnResponse($response, $logFile, $clientIP);
        exit;
    }
    
    // Search clients with partial match
    $clientsLikeSql = "SELECT c.id, c.name, su.email, su.phone, su.mobile
                       FROM clients c 
                       JOIN site_users su ON c.primary_contact = su.id
                       WHERE (su.phone LIKE ? OR su.mobile LIKE ?) AND c.deleted_at IS NULL
                       LIMIT 1";
    $stmt = $pdo->prepare($clientsLikeSql);
    $stmt->execute([$searchPattern, $searchPattern]);
    $clientPartialMatch = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($clientPartialMatch) {
        $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | PARTIAL: client #' . $clientPartialMatch['id'] . ' ' . $clientPartialMatch['name'] . PHP_EOL;
        file_put_contents($logFile, $logEntry, FILE_APPEND | LOCK_EX);
        
        $response = generateResponse($clientPartialMatch, 'partial', 'client', $appUrl, $cleanNumber);
        logAndReturnResponse($response, $logFile, $clientIP);
    }
    
    // No match found
    $logEntry = '[' . date('Y-m-d H:i:s') . '] IP: ' . $clientIP . ' | NO MATCH for: ' . $cleanNumber . PHP_EOL;
    $logEntry .= str_repeat('-', 80) . 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') . '] IP: ' . $clientIP . ' | ERROR: ' . substr($e->getMessage(), 0, 50) . PHP_EOL;
    $logEntry .= str_repeat('-', 80) . 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()
    ]);
}
?>