<?php
require_once 'includes/config.php';

// Get latest 10 calls
$stmt = $db->query("SELECT * FROM target_numbers 
    ORDER BY call_date DESC LIMIT 10");
$calls = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get latest call status
$latest_call = null;
if (!empty($calls)) {
    $latest_call = $calls[0];
}

$html = '';
foreach ($calls as $call) {
    $badgeClass = 'bg-secondary';
    if ($call['status'] === 'Success') {
        $badgeClass = 'bg-success';
    } else if ($call['status'] === '-') {
        $badgeClass = 'bg-warning';
    }
    
    $actionStatus = '-';
    if ($call['pressed_button'] === '1') {
        $actionStatus = '<span class="badge bg-success">Completed</span>';
    } else if ($call['call_date'] && 
        $call['status'] === '-' && 
            $call['pressed_button'] === null &&
            $call['call_sid'] !== null) {
        $actionStatus = '<span class="badge bg-warning">Calling</span>';
    }
    
    $html .= '<tr>';
    $html .= '<td>' . htmlspecialchars($call['phone_number']) . '</td>';
    $html .= '<td>' . htmlspecialchars($call['pressed_button'] ?? '-') . '</td>';
    $html .= '<td><span class="badge ' . $badgeClass . '">' . htmlspecialchars($call['status']) . '</span></td>';
    $html .= '<td>' . ($call['call_date'] ? date('d-M-Y H:i:s', strtotime($call['call_date'])) : '-') . '</td>';
    $html .= '<td>' . $actionStatus . '</td>';
    $html .= '</tr>';
}

if (empty($calls)) {
    $html = '<tr><td colspan="5" class="text-center">No data available</td></tr>';
}

// Get updated statistics
$stmt = $db->query("SELECT 
    COUNT(*) as total_calls,
    SUM(CASE WHEN status = 'Success' THEN 1 ELSE 0 END) as success_calls,
    SUM(CASE WHEN status = '-' THEN 1 ELSE 0 END) as pending_calls
FROM target_numbers");
$stats = $stmt->fetch(PDO::FETCH_ASSOC);

// Hitung panggilan aktif (sekarang hanya 1 atau 0)
$stmt = $db->query("SELECT COUNT(*) as active_calls 
    FROM target_numbers 
    WHERE status = '-' 
    AND call_date IS NOT NULL 
    AND pressed_button IS NULL
    AND call_date >= DATE_SUB(NOW(), INTERVAL 30 SECOND)");
$active_calls = $stmt->fetch(PDO::FETCH_ASSOC)['active_calls'];

// Hitung sisa nomor yang belum dipanggil
$stmt = $db->query("SELECT COUNT(*) as remaining_calls 
    FROM target_numbers 
    WHERE status = '-' 
    AND (
        call_date IS NULL 
        OR (
            call_date IS NOT NULL 
            AND call_date < DATE_SUB(NOW(), INTERVAL 30 SECOND)
            AND pressed_button IS NULL
        )
    )");
$remaining_calls = $stmt->fetch(PDO::FETCH_ASSOC)['remaining_calls'];

// Cek apakah panggilan terakhir baru saja selesai
$stmt = $db->query("SELECT COUNT(*) as recent_completed 
    FROM target_numbers 
    WHERE call_date IS NOT NULL 
    AND call_date >= DATE_SUB(NOW(), INTERVAL 30 SECOND)
    AND (status = 'Success' OR pressed_button IS NOT NULL)");
$recent_call = $stmt->fetch(PDO::FETCH_ASSOC)['recent_completed'] > 0;

$response = [
    'table_html' => $html,
    'stats' => [
        'total_calls' => $stats['total_calls'],
        'success_calls' => $stats['success_calls'],
        'pending_calls' => $stats['pending_calls']
    ],
    'active_calls' => (int)$active_calls,
    'remaining_calls' => (int)$remaining_calls,
    'recent_call' => $recent_call
];

// Debug log
error_log('Response data: ' . print_r($response, true));

header('Content-Type: application/json');
echo json_encode($response); 