<?php
// sms_functions2.php
// Pure helper library. Do NOT include db_connect.php inside this file.
// Caller must include db_connect.php first so $conn exists.

// --- BEEM API credentials (replace with real values if different) ---
if (!defined('BEEM_API_KEY')) define('BEEM_API_KEY', '4d2495c90cbee253');
if (!defined('BEEM_SECRET_KEY')) define('BEEM_SECRET_KEY', 'MWVkOWQzYWM5Yjg1MmNiNDA2ZGRiODZkODI3ZDQ0OTk4ODBmNzhmYTU5Mzg3YmM5Y2M5Y2ZkN2Q0OGI3ZTJlMw==');
if (!defined('BEEM_API_URL')) define('BEEM_API_URL', 'https://apisms.beem.africa/v1/send');

/**
 * Get current local SMS balance from Kigango_SMS_Balance.
 * @param mysqli $conn
 * @return int
 */
function getLocalSmsBalance($conn) {
    $sql = "SELECT current_balance FROM Kigango_SMS_Balance LIMIT 1";
    $stmt = $conn->prepare($sql);
    if (!$stmt) return 0;
    $stmt->execute();
    $res = $stmt->get_result();
    $balance = 0;
    if ($res && ($r = $res->fetch_assoc())) {
        $balance = (int)$r['current_balance'];
    }
    $stmt->close();
    return $balance;
}

/**
 * Decrement local SMS balance by $decrement (default 1).
 * @param mysqli $conn
 * @param int $decrement
 * @return bool
 */
function updateSmsBalance($conn, $decrement = 1) {
    $sql = "UPDATE Kigango_SMS_Balance SET current_balance = current_balance - ? WHERE current_balance >= ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    if (!$stmt) return false;
    $stmt->bind_param('ii', $decrement, $decrement);
    $ok = $stmt->execute();
    $stmt->close();
    return (bool)$ok;
}

/**
 * Log SMS to SMS_Log table.
 *
 * @param mysqli $conn
 * @param array $logData
 * @return bool
 */
function logSms($conn, array $logData) {
    $sql = "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, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        error_log("logSms prepare failed: " . $conn->error);
        return false;
    }

    // Normalize values
    $recipient_phone       = $logData['recipient_phone'] ?? '';
    $message_content       = $logData['message_content'] ?? '';
    $sent_status           = $logData['sent_status'] ?? 'failed';
    $beem_request_id       = $logData['beem_request_id'] ?? '';
    $api_response          = $logData['api_response'] ?? '';
    $sms_category_id       =4;
   // $sms_category_id       = isset($logData['sms_category_id']) ? intval($logData['sms_category_id']) : 0;
    $related_contribution_id = isset($logData['related_contribution_id']) ? intval($logData['related_contribution_id']) : 0;
    $authorized_person_id  = isset($logData['authorized_person_id']) ? intval($logData['authorized_person_id']) : 0;
    $partner_id            = $logData['partner_id'] ?? '';
    $partner_code          = $logData['partner_code'] ?? '';
    $monthYear             = $logData['monthYear'] ?? date('F Y');

    // Correct binding (5 strings + 3 ints + 3 strings)
    $stmt->bind_param(
        "sssssiiisss",
        $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
    );

    $ok = $stmt->execute();
    if (!$ok) {
        error_log("logSms execute failed: " . $stmt->error);
    }
    $stmt->close();
    return (bool)$ok;
}

/**
 * Send SMS via Beem.
 *
 * @param mysqli $conn
 * @param string $recipient_phone
 * @param string $message
 * @return array
 */
function sendBeemSms($conn, $recipient_phone, $message) {
    $balance = getLocalSmsBalance($conn);
    if ($balance <= 0) {
        return [
            'status' => 'failed',
            'beem_request_id' => null,
            'api_response' => json_encode(['error' => 'Local SMS balance is zero']),
            'skipped' => true
        ];
    }

    $payload = [
        'source_addr' => 'OCOAN',
        'encoding' => 0,
        'schedule_time' => '',
        'message' => $message,
        'recipients' => [
            ['recipient_id' => '1', 'dest_addr' => $recipient_phone]
        ]
    ];

    $ch = curl_init(BEEM_API_URL);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Basic ' . base64_encode(BEEM_API_KEY . ':' . BEEM_SECRET_KEY),
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $resp = curl_exec($ch);
    $curlErr = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($resp === false || $httpCode >= 400) {
        $api_response = $resp !== false ? $resp : json_encode(['curl_error' => $curlErr, 'http_code' => $httpCode]);
        return [
            'status' => 'failed',
            'beem_request_id' => null,
            'api_response' => $api_response,
            'skipped' => false
        ];
    }

    $decoded = json_decode($resp, true);
    $successful = 0;
    $beem_request_id = null;

    if (isset($decoded['successful'])) {
        $successful = (int)$decoded['successful'];
        $beem_request_id = $decoded['request_id'] ?? null;
    } elseif (!empty($decoded['results']) && is_array($decoded['results'])) {
        foreach ($decoded['results'] as $r) {
            if (!empty($r['status']) && in_array(strtolower($r['status']), ['success', 'sent'])) {
                $successful++;
            }
        }
        $beem_request_id = $decoded['results'][0]['request_id'] ?? null;
    }

    $status = ($successful > 0) ? 'sent' : 'failed';

    if ($status === 'sent') {
        updateSmsBalance($conn, 1);
    }

    return [
        'status' => $status,
        'beem_request_id' => $beem_request_id,
        'api_response' => $resp,
        'skipped' => false
    ];
}
