<?php

// send_confirm_registration_sms.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!file_exists('db_connect.php')) {
    die("Error: The 'db_connect.php' file was not found. Please ensure it's in the same directory.");
}
include 'db_connect.php';

// --- FUNCTIONS ---
function getLocalSmsBalance($conn) {
    $sql = "SELECT current_balance FROM Kigango_SMS_Balance LIMIT 1";
    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        return (int) $row['current_balance'];
    }
    return 0;
}

function updateSmsBalance($conn) {
    $sql = "UPDATE Kigango_SMS_Balance SET current_balance = current_balance - 1 WHERE current_balance > 0 LIMIT 1";
    return $conn->query($sql);
}

function logSms($conn, $logData) {
    $stmt = $conn->prepare("INSERT INTO SMS_Log (recipient_phone, message_content, sent_status, beem_request_id, api_response, sms_category_id, related_contribution_id, authorized_person_id, partner_id, partner_code, monthYear) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    if ($stmt === false) {
        error_log("Prepare failed: " . $conn->error);
        return false;
    }

    $stmt->bind_param("sssssiisiss",
        $logData['recipient_phone'],
        $logData['message_content'],
        $logData['sent_status'],
        $logData['beem_request_id'],
        $logData['api_response'],
        $logData['sms_category_id'],
        $logData['related_contribution_id'],
        $logData['authorized_person_id'],
        $logData['partner_id'],
        $logData['partner_code'],
        $logData['monthYear']
    );

    $result = $stmt->execute();
    if ($result === false) {
        error_log("Execute failed: " . $stmt->error);
    }
    $stmt->close();
    return $result;
}

function sendBeemSms($recipient, $message) {
    $api_key = '4d2495c90cbee253';
    $secret_key = 'MWVkOWQzYWM5Yjg1MmNiNDA2ZGRiODZkODI3ZDQ0OTk4ODBmNzhmYTU5Mzg3YmM5Y2M5Y2ZkN2Q0OGI3ZTJlMw==';
    $source_addr = 'OCOAN';

    $postData = array(
        'source_addr' => $source_addr,
        'encoding' => 0,
        'schedule_time' => '',
        'message' => $message,
        'recipients' => [
            array(
                'recipient_id' => '1',
                'dest_addr' => $recipient
            )
        ]
    );

    $url = 'https://apisms.beem.africa/v1/send';

    $ch = curl_init($url);
    curl_setopt_array($ch, array(
        CURLOPT_POST => TRUE,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_HTTPHEADER => array(
            'Authorization:Basic ' . base64_encode("$api_key:$secret_key"),
            'Content-Type: application/json'
        ),
        CURLOPT_POSTFIELDS => json_encode($postData),
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0
    ));

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $responseData = json_decode($response, true);
    $result = [
        'status' => 'Failed',
        'beem_request_id' => null,
        'api_response' => $response,
        'error_message' => 'Unknown error.'
    ];

    if ($httpCode == 200 && isset($responseData['successful']) && $responseData['successful'] === true) {
        $result['status'] = 'Sent';
        $result['beem_request_id'] = $responseData['request_id'] ?? null;
        $result['error_message'] = null;
    } else {
        $result['error_message'] = 'HTTP Code ' . $httpCode . ' Response: ' . $response;
        error_log('Beem SMS API Error: ' . $result['error_message']);
    }

    return $result;
}
// --- END FUNCTIONS ---

header('Content-Type: application/json');

// ✅ Accept both POST and GET
$partner_id = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['partner_id'])) {
    $partner_id = (int) $_POST['partner_id'];
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'])) {
    $partner_id = (int) $_GET['id'];
}

if ($partner_id) {
    $response = ['status' => 'error', 'message' => 'Invalid request.'];

    $stmt = $conn->prepare("SELECT partner_name, partner_code, phone_number1 FROM Partners WHERE partner_id = ?");
    $stmt->bind_param("i", $partner_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $partner = $result->fetch_assoc();
        $partner_name = $partner['partner_name'];
        $partner_code = $partner['partner_code'];
        $phone_number = $partner['phone_number1'];
        $authorized_person_id = '1';
        $sms_category_id = 3;
        
        
        
    // ✅ ADD THIS BLOCK HERE
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $response = [
            "status" => "success",
            "partner_name" => $partner['partner_name'] ?? "",
            "partner_code" => $partner['partner_code'] ?? "",
            "recipient_phone" => $partner['phone_number1'] ?? "",
            "full_message" => "Nguvu ya Omega, ndugu " . ($partner['partner_name'] ?? "") .
                              ", umesajiliwa kwenye Haleluya TV partner na namba yako ni: " .
                              ($partner['partner_code'] ?? "")
        ];
        header('Content-Type: application/json');
        echo json_encode($response);
        exit;
    }
    // ✅ END ADD BLOCK

        $sms_message = "Nguvu ya Omega, ndugu {$partner_name}, umesajiliwa kwenye Haleluya TV partner na namba yako ni: {$partner_code}";

        $balance = getLocalSmsBalance($conn);
        if ($balance < 1) {
            $response['message'] = "⚠️ Low Balance! Your available SMS balance is " . $balance . ". Please recharge.";
            $logData = [
                'recipient_phone' => $phone_number,
                'message_content' => $sms_message,
                'sent_status' => 'Failed - Low Balance',
                'beem_request_id' => null,
                'api_response' => 'Skipped due to low balance',
                'sms_category_id' => $sms_category_id,
                'related_contribution_id' => null,
                'authorized_person_id' => $authorized_person_id,
                'partner_id' => $partner_id,
                'partner_code' => $partner_code,
                'monthYear' => date('F Y')
            ];
            logSms($conn, $logData);
            echo json_encode($response);
            exit;
        }

        $send_result = sendBeemSms($phone_number, $sms_message);

        if ($send_result['status'] === 'Sent') {
            updateSmsBalance($conn);
            $response['status'] = 'success';
            $response['message'] = "SMS sent successfully! Status: " . $send_result['status'];
        } else {
            $response['status'] = 'error';
            $response['message'] = "SMS sending failed. Error: " . ($send_result['error_message'] ?? 'Unknown');
        }

        $logData = [
            'recipient_phone' => $phone_number,
            'message_content' => $sms_message,
            'sent_status' => $send_result['status'],
            'beem_request_id' => $send_result['beem_request_id'],
            'api_response' => $send_result['api_response'],
            'sms_category_id' => $sms_category_id,
            'related_contribution_id' => null,
            'authorized_person_id' => $authorized_person_id,
            'partner_id' => $partner_id,
            'partner_code' => $partner_code,
            'monthYear' => date('F Y')
        ];
        if (!logSms($conn, $logData)) {
            $response['status'] = 'error';
            $response['message'] .= " Failed to log SMS.";
        }
    } else {
        $response['message'] = 'Partner not found.';
    }

    $stmt->close();
    $conn->close();
    echo json_encode($response);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request.']);
}
