<?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'] ?? '';
    $digits = $_POST['Digits'] ?? null;

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

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

        // Jangan update jika status sudah Success
        if ($currentStatus === 'Success') {
            error_log("Skipping update - number 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 hanya jika status bukan Success
        $stmt = $db->prepare("
            UPDATE target_numbers 
            SET status = ?,
                pressed_button = ?,
                call_date = NOW()
            WHERE phone_number = ? 
            AND (status != 'Success' OR status IS NULL)
        ");
        
        $stmt->execute([$status, $pressed, $to]);
        error_log("Updated status for $to to $status with pressed button $pressed");
    }

    // 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()]);
} 