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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Debug Twilio configuration
        error_log("Twilio Configuration:");
        error_log("Base URL: " . BASE_URL);
        error_log("Webhook URL: " . WEBHOOK_URL);
        error_log("Twilio Number: " . TWILIO_NUMBER);

        // Get next number to call from all numbers in the table
        $stmt = $db->prepare("SELECT id, phone_number, status FROM target_numbers ORDER BY id ASC LIMIT 1");
        $stmt->execute();
        $number = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$number) {
            throw new Exception('No phone numbers found in database.');
        }

        // Debug log
        error_log("Found number to call: " . print_r($number, true));

        // Initialize Twilio client
        $client = getTwilioClient();

        // Make the call with modified configuration
        $call = $client->calls->create(
            $number['phone_number'], // To
            TWILIO_NUMBER,          // From
            [
                'url' => WEBHOOK_URL,
                'method' => 'POST',
                'statusCallback' => WEBHOOK_URL,
                'statusCallbackMethod' => 'POST',
                'statusCallbackEvent' => ['completed', 'failed', 'no-answer'],
                'fallbackUrl' => WEBHOOK_URL,
                'fallbackMethod' => 'POST'
            ]
        );

        // Log call SID
        error_log("Call created with SID: " . $call->sid);

        // Update database with call SID and reset status to N/A for new call attempt
        $stmt = $db->prepare("UPDATE target_numbers SET call_sid = ?, status = 'N/A', pressed_button = NULL, call_date = NOW() WHERE id = ?");
        $stmt->execute([$call->sid, $number['id']]);

        $response = [
            'success' => true,
            'message' => 'Call initiated to ' . $number['phone_number'] . ' (Previous status: ' . $number['status'] . ')',
            'number' => $number['phone_number']
        ];

    } catch (Exception $e) {
        error_log("Call error: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
        
        $response = [
            'success' => false,
            'message' => $e->getMessage()
        ];
    }

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