#!/bin/bash
# DECT Auto Discovery Script - UPDATE ONLY (no auto-create)
cd /var/www/html

# Get SIP contacts
asterisk -rx "pjsip show contacts" 2>/dev/null | grep -E "Contact.*sip:" | while read line; do
    contact_id=$(echo "$line" | grep -oP 'Contact:\s+\K\S+(?=/sip:)')
    ip=$(echo "$line" | grep -oP '@\K[0-9.]+(?=:)')
    
    # Skip localhost and non-numeric
    if [[ "$ip" == "127.0.0.1" ]] || [[ "$ip" == "localhost" ]]; then
        continue
    fi
    
    extension=$(echo "$contact_id" | grep -oP '^\d+')
    if [ -z "$extension" ]; then
        continue
    fi
    
    ep_info=$(asterisk -rx "pjsip show endpoint $extension" 2>/dev/null)
    user_agent=$(echo "$ep_info" | grep -i "user_agent" | cut -d: -f2- | xargs)
    
    echo "$extension|$ip|$user_agent" >> /tmp/dect_contacts.txt
done

php << 'ENDPHP'
<?php
require '/var/www/html/vendor/autoload.php';
$app = require_once '/var/www/html/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

use App\Models\Dect\DectHandset;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

if (!file_exists('/tmp/dect_contacts.txt')) {
    Log::info('DECT Discovery: No contacts found');
    exit(0);
}

$lines = file('/tmp/dect_contacts.txt', FILE_IGNORE_NEW_LINES);
unlink('/tmp/dect_contacts.txt');

$contacts = [];
$dectPatterns = ['W70', 'W80', 'W90', 'W56', 'W57', 'W59', 'W73', 'W78'];

foreach ($lines as $line) {
    $parts = explode('|', $line);
    if (count($parts) >= 2) {
        $ext = $parts[0];
        $ip = $parts[1];
        $ua = $parts[2] ?? '';
        
        // Check if User-Agent indicates DECT device
        $isDect = false;
        $uaUpper = strtoupper($ua);
        foreach ($dectPatterns as $pattern) {
            if (strpos($uaUpper, $pattern) !== false) {
                $isDect = true;
                break;
            }
        }
        
        $contacts[] = [
            'extension' => $ext,
            'ip' => $ip,
            'user_agent' => $ua,
            'is_dect' => $isDect,
        ];
    }
}

// Group by IP
$ipGroups = [];
foreach ($contacts as $contact) {
    $ip = $contact['ip'];
    if (!isset($ipGroups[$ip])) {
        $ipGroups[$ip] = ['contacts' => [], 'has_dect_ua' => false];
    }
    $ipGroups[$ip]['contacts'][] = $contact;
    if ($contact['is_dect']) {
        $ipGroups[$ip]['has_dect_ua'] = true;
    }
}

$stats = ['updated' => 0, 'offline' => 0, 'skipped' => 0];

// Get all currently configured handsets
$existingHandsets = DectHandset::whereNotNull('extension_id')->get();
$existingExts = [];
foreach ($existingHandsets as $h) {
    $exten = DB::table('extensions')->where('id', $h->extension_id)->value('exten');
    if ($exten) {
        $existingExts[$exten] = $h;
    }
}

// Only process IPs that have DECT User-Agent or multiple contacts
$activeExts = [];
foreach ($ipGroups as $ip => $group) {
    $hasDectUa = $group['has_dect_ua'];
    
    foreach ($group['contacts'] as $contact) {
        $ext = $contact['extension'];
        
        // ONLY update if handset already exists in database
        if (!isset($existingExts[$ext])) {
            $stats['skipped']++;
            continue;
        }
        
        $activeExts[] = $ext;
        $handset = $existingExts[$ext];
        
        // Determine model
        $model = 'W73H';
        $ua = strtoupper($contact['user_agent']);
        if (strpos($ua, 'W70') !== false) $model = 'W70B';
        elseif (strpos($ua, 'W80') !== false) $model = 'W80B';
        elseif (strpos($ua, 'W90') !== false) $model = 'W90B';
        elseif (strpos($ua, 'W56') !== false) $model = 'W56H';
        elseif (strpos($ua, 'W57') !== false) $model = 'W57R';
        elseif (strpos($ua, 'W59') !== false) $model = 'W59R';
        elseif (strpos($ua, 'W78') !== false) $model = 'W78H';
        
        // Update existing handset
        $handset->update([
            'status' => 'active',
            'model' => $model,
            'settings' => json_encode([
                'discovered_ip' => $ip,
                'discovered_at' => now()->toIso8601String(),
                'user_agent' => $contact['user_agent'],
            ]),
            'updated_at' => now(),
        ]);
        $stats['updated']++;
    }
}

// Mark configured handsets as offline if not seen
foreach ($existingHandsets as $handset) {
    $exten = DB::table('extensions')->where('id', $handset->extension_id)->value('exten');
    if ($exten && !in_array($exten, $activeExts)) {
        $handset->update(['status' => 'offline']);
        $stats['offline']++;
    }
}

Log::info('DECT Discovery completed', $stats);
echo "Discovery: {$stats['updated']} handsets updated, {$stats['offline']} marked offline, {$stats['skipped']} not configured\n";
ENDPHP

