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

// Matikan error reporting untuk production
error_reporting(0);
ini_set('display_errors', 0);

try {
    // Ambil status panggilan dari Twilio
    $callStatus = $_POST['CallStatus'] ?? '';
    $to = $_POST['To'] ?? '';
    $callSid = $_POST['CallSid'] ?? '';
    $digits = $_POST['Digits'] ?? null;

    // Log untuk debugging
    error_log("Callback received - Status: $callStatus, To: $to, CallSid: $callSid, Digits: $digits");

    // Update status berdasarkan kondisi
    if ($callSid) {
        // Cek status panggilan saat ini
        $stmt = $db->prepare("SELECT status FROM target_numbers WHERE call_sid = ?");
        $stmt->execute([$callSid]);
        $currentStatus = $stmt->fetchColumn();

        // Jangan update jika status sudah Success
        if ($currentStatus === 'Success') {
            error_log("Skipping update - call already has Success status");
            echo json_encode(['success' => true]);
            exit;
        }

        $status = '-';
        $pressed = '-';

        if ($callStatus === 'completed') {
            if (isset($_POST['Digits']) && $_POST['Digits'] === '1') {
                $status = 'Success';
                $pressed = '1';
            }
        } else if (in_array($callStatus, ['busy', 'failed', 'no-answer', 'canceled'])) {
            $status = '-';
            $pressed = '-';
        }

        // Update database menggunakan call_sid
        $stmt = $db->prepare("
            UPDATE target_numbers 
            SET status = ?,
                pressed_button = ?,
                call_date = NOW()
            WHERE call_sid = ? 
            AND (status != 'Success' OR status IS NULL)
        ");
        
        $stmt->execute([$status, $pressed, $callSid]);
        error_log("Updated status for CallSid: $callSid to $status with pressed button $pressed");

        // Cek apakah semua panggilan sudah selesai
        $stmt = $db->prepare("
            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)
        ");
        $stmt->execute();
        $active_calls = $stmt->fetchColumn();

        // Jika tidak ada panggilan aktif, cek apakah ada sisa panggilan
        if ($active_calls === 0) {
            $stmt = $db->prepare("
                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
                    )
                )
            ");
            $stmt->execute();
            $remaining_calls = $stmt->fetchColumn();

            // Jika tidak ada sisa panggilan, bersihkan data panggilan yang gagal
            if ($remaining_calls === 0) {
                error_log("No remaining calls, cleaning up failed calls data");
                
                // Bersihkan data panggilan yang gagal (status '-' dan bukan Success)
                $stmt = $db->prepare("
                    UPDATE target_numbers 
                    SET call_sid = NULL,
                        call_date = NULL,
                        created_at = CURRENT_TIMESTAMP
                    WHERE status = '-'
                    AND pressed_button IS NOT NULL  /* Pastikan panggilan sudah selesai */
                    AND pressed_button != '1'       /* Bukan panggilan sukses */
                ");
                
                $result = $stmt->execute();
                
                if ($result) {
                    $affected = $stmt->rowCount();
                    error_log("Successfully cleaned up {$affected} failed call records");
                } else {
                    error_log("Failed to clean up call data: " . implode(", ", $stmt->errorInfo()));
                }
            }
        }

        // Clean output dan kirim response
        ob_clean();
        header('Content-Type: application/json');
        echo json_encode(['success' => true]);
        
    }

} catch (Exception $e) {
    error_log("Callback error: " . $e->getMessage());
    ob_clean();
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
} 