<?php
// send_sms_for_partners_view_general_Contribution_details.php

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// --- BEEM API credentials ---
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');

// -------------------------------------------------------------
// --- Helper Functions ---
// -------------------------------------------------------------

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;
}

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 into SMS_Log with only allowed fields
 */
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
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($sql);
    if ($stmt === false) {
        error_log("logSms 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']
    );

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

/**
 * Send SMS via Beem with detailed error reporting
 */
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
        ];
    }

  // normalize phone number
$recipient_phone = preg_replace('/[^0-9]/', '', $recipient_phone);

// ✅ If phone already starts with "255", do not add another "255"
if (substr($recipient_phone, 0, 3) === '255' && strlen($recipient_phone) === 12) {
    // Already in correct format, leave it as is
} elseif (strlen($recipient_phone) == 10 && $recipient_phone[0] == '0') {
    $recipient_phone = '255' . substr($recipient_phone, 1);
} elseif (strlen($recipient_phone) == 9 && $recipient_phone[0] == '7') {
    $recipient_phone = '255' . $recipient_phone;
}

if (strlen($recipient_phone) !== 12 || substr($recipient_phone, 0, 3) !== '255') {
    return [
        'status' => 'failed',
        'beem_request_id' => null,
        'api_response' => json_encode(['error' => 'Invalid phone format: ' . $recipient_phone]),
        'skipped' => false
    ];
}


    $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_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Basic ' . base64_encode(BEEM_API_KEY . ':' . BEEM_SECRET_KEY),
            'Content-Type: application/json'
        ],
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_CONNECTTIMEOUT => 10,
        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) {
        return [
            'status' => 'failed',
            'beem_request_id' => null,
            'api_response' => json_encode([
                'curl_error' => $curlErr,
                'http_code' => $httpCode,
                'raw_response' => $resp
            ]),
            'skipped' => false
        ];
    }

    $decoded = json_decode($resp, true);
    $successful = 0;
    $beem_request_id = $decoded['request_id'] ?? null;

    if (!empty($decoded['results'])) {
        foreach ($decoded['results'] as $r) {
            if (!empty($r['status']) && in_array(strtolower($r['status']), ['success', 'sent'])) {
                $successful++;
            }
        }
    }

    $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
    ];
}

// -------------------------------------------------------------
// --- Main Execution ---
// -------------------------------------------------------------

include 'db_connect.php';

function get_safe_post_data($param, $default = '') {
    return isset($_POST[$param]) ? trim($_POST[$param]) : $default;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $partner_id = get_safe_post_data('partner_id');
    $partner_code = get_safe_post_data('partner_code');
    $phone_number = get_safe_post_data('phone_number');
    $month_year = get_safe_post_data('month_year');
    $sms_category_id = get_safe_post_data('sms_category_id');
    $message_content = get_safe_post_data('message_content');
    $partner_query_filter = get_safe_post_data('partner_query_filter');

    if (!$partner_id || !$partner_code || !$phone_number || !$month_year || !$sms_category_id || !$message_content) {
        $_SESSION['sms_status'] = ['type' => 'danger', 'message' => 'Please fill in all required fields.'];
        header("Location: partnership_contributions.php?month_year_filter=" . urlencode($month_year));
        exit();
    }

    $beem_response = sendBeemSms($conn, $phone_number, $message_content);
    $sms_sent_successfully = ($beem_response['status'] === 'sent');

    $log_data = [
        'recipient_phone'       => $phone_number,
        'message_content'       => $message_content,
        'sent_status'           => $beem_response['status'],
        'beem_request_id'       => $beem_response['beem_request_id'],
        'api_response'          => $beem_response['api_response'],
        'sms_category_id'       => $sms_category_id,
        'related_contribution_id' => null,
        'authorized_person_id'    => $_SESSION['user_id'] ?? null,
        'partner_id'            => $partner_id,
        'partner_code'          => $partner_code,
        'monthYear'             => $month_year
    ];

    $log_success = logSms($conn, $log_data);

    if ($sms_sent_successfully) {
        $_SESSION['sms_status'] = ['type' => 'success', 'message' => 'SMS sent successfully to ' . $phone_number];
    } elseif ($beem_response['skipped']) {
        $err = json_decode($beem_response['api_response'], true)['error'] ?? 'Unknown';
        $_SESSION['sms_status'] = ['type' => 'warning', 'message' => 'SMS not sent. Reason: ' . $err];
    } else {
        $_SESSION['sms_status'] = [
            'type' => 'danger',
            'message' => 'Error sending SMS. Details: ' . $beem_response['api_response']
        ];
    }

    if ($sms_sent_successfully && !$log_success) {
        $_SESSION['sms_status']['type'] = 'warning';
        $_SESSION['sms_status']['message'] .= ' | WARNING: SMS not logged in DB.';
    }

    header("Location: partnership_contributions.php?month_year_filter=" . urlencode($month_year) . "&partner_query_filter=" . urlencode($partner_query_filter));
    exit();
} else {
    $_SESSION['sms_status'] = ['type' => 'danger', 'message' => 'Invalid request method.'];
    header("Location: partnership_contributions.php");
    exit();
}

$conn->close();
?>
