<?php
require_once 'config.php';

// Start Session
// Session started in config.php

/**
 * Send Single SMS using BulkSMSBD.net API
 */
function send_sms_single($to, $message)
{
    $url = SMS_API_URL_ONE;
    $data = [
        'api_key' => SMS_API_KEY,
        'senderid' => SMS_SENDER_ID,
        'number' => $to,
        'message' => $message
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

/**
 * Send Many SMS (Bulk) using BulkSMSBD.net API
 * $messages format: [['to' => '...', 'message' => '...'], ...]
 */
function send_sms_many($messages_array)
{
    $url = SMS_API_URL_MANY;
    $messages_json = json_encode($messages_array);
    $data = [
        'api_key' => SMS_API_KEY,
        'senderid' => SMS_SENDER_ID,
        'messages' => $messages_json
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

/**
 * Get SMS Error Message from Code
 */
function get_sms_error_message($code)
{
    if (strpos($code, '202') !== false)
        return "SMS Submitted Successfully"; // API returns 202xxxxx sometimes
    $codes = [
        '1001' => 'Invalid Number',
        '1002' => 'Sender ID not correct or disabled',
        '1003' => 'All fields required or Contact Admin',
        '1005' => 'Internal Error',
        '1006' => 'Balance Validity Not Available',
        '1007' => 'Balance Insufficient',
        '1011' => 'User Id not found',
        '1012' => 'Masking SMS must be sent in Bengali',
        '1013' => 'Sender Id has not found Gateway by api key',
        '1014' => 'Sender Type Name not found by api key',
        '1015' => 'Sender Id has not found Any Valid Gateway',
        '1016' => 'Sender Type Name Active Price Info not found',
        '1017' => 'Sender Type Name Price Info not found',
        '1018' => 'The Owner of this Account is disabled',
        '1019' => 'The Price of this Account is disabled',
        '1020' => 'The parent of this account is not found',
        '1021' => 'The parent active price of this account is not found',
        '1031' => 'Your Account Not Verified, Please Contact Administrator',
        '1032' => 'IP Not whitelisted'
    ];
    return $codes[$code] ?? "Unknown Error: " . $code;
}

/**
 * Get SMS Balance
 */
function get_sms_balance()
{
    // Deprecated in favor of get_balance()
    return get_balance();
}

/**
 * Get Balance from BulkSMSBD.net
 */
function get_balance()
{
    $url = "http://bulksmsbd.net/api/getBalanceApi?api_key=" . SMS_API_KEY;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // Use GET method clearly
    curl_setopt($ch, CURLOPT_HTTPGET, true);

    $response = curl_exec($ch);
    curl_close($ch);

    // Robust parsing: Try JSON first, otherwise return raw
    $json = json_decode($response, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        if (isset($json['balance_amount']))
            return $json['balance_amount'];
        if (isset($json['balance']))
            return $json['balance'];
        // Add other keys if known, otherwise return raw if no known key found
    }

    return $response;
}

/**
 * Check Admin Authentication
 */
function check_admin_auth()
{
    if (!isset($_SESSION['admin_id'])) {
        // Check "Remember Me" Cookie
        if (isset($_COOKIE['admin_remember'])) {
            // Logic to validate cookie token (simplified for now)
            // In production, validate token against DB
            $_SESSION['admin_id'] = $_COOKIE['admin_remember']; // Insecure simplified
        } else {
            header("Location: " . base_url('public/index.php'));
            exit;
        }
    }
}

/**
 * Check User Authentication
 */
function check_user_auth()
{
    if (!isset($_SESSION['user_id'])) {
        if (isset($_COOKIE['user_remember'])) {
            $_SESSION['user_id'] = $_COOKIE['user_remember'];
        } else {
            header("Location: " . base_url('public/user_login.php'));
            exit;
        }
    }
}

/**
 * Check if User is Logged In (Boolean)
 */
function is_logged_in()
{
    return isset($_SESSION['user_id']);
}

/**
 * Helper to send json response
 */
function json_response($status, $message, $data = [])
{
    header('Content-Type: application/json');
    echo json_encode(['status' => $status, 'message' => $message, 'data' => $data]);
    exit;
}

/**
 * Auto-Save Contact if not exists
 */
function auto_save_contact($owner_type, $owner_id, $number)
{
    global $pdo;

    // Validate number
    $number = trim($number);
    if (empty($number))
        return;

    try {
        if ($owner_type === 'admin') {
            // Admin: Check if number exists anywhere in the system
            $stmt = $pdo->prepare("SELECT id FROM contacts WHERE phone_number = ? LIMIT 1");
            $stmt->execute([$number]);
            if ($stmt->rowCount() > 0) {
                return; // Already exists, admin sees all, so no need to duplicate
            }
        } else {
            // User: Check if they already own it
            $stmt = $pdo->prepare("SELECT id FROM contacts WHERE owner_type = ? AND owner_id = ? AND phone_number = ?");
            $stmt->execute([$owner_type, $owner_id, $number]);
            if ($stmt->rowCount() > 0) {
                return; // Already owned
            }
        }

        // Insert if we passed the checks
        $ins = $pdo->prepare("INSERT INTO contacts (owner_type, owner_id, phone_number, user_id) VALUES (?, ?, ?, ?)");
        // If owner is user, set user_id too for legacy compat
        $u_id = ($owner_type === 'user') ? $owner_id : null;
        $ins->execute([$owner_type, $owner_id, $number, $u_id]);

    } catch (PDOException $e) {
        // Silent failure
    }
}

/**
 * Log SMS to Database
 */
/**
 * Log SMS to Database
 */
function log_sms($user_id, $sender_id, $recipient, $message, $status, $api_response, $owner_type = 'user', $owner_id = 0)
{
    global $pdo;

    // Use explicit owner_id if provided, otherwise fallback to user_id
    $final_owner_id = ($owner_id) ? $owner_id : ($user_id ? $user_id : 0);

    // Auto-save the contact
    auto_save_contact($owner_type, $final_owner_id, $recipient);

    $stmt = $pdo->prepare("INSERT INTO sms_logs (user_id, sender_id, recipient_number, message_body, status, api_response) VALUES (?, ?, ?, ?, ?, ?)");
    // sms_logs.user_id FK might fail if we pass Admin ID. 
    // For now, pass user_id (nullable) as is.
    $stmt->execute([$user_id, $sender_id, $recipient, $message, $status, $api_response]);
}

/**
 * Get Base URL of the application
 */
function base_url($path = '')
{
    // Check if BASE_URL ends with / and path starts with / to avoid double slash
    $base = BASE_URL;
    $path = ltrim($path, '/');
    return $base . $path;
}

/**
 * Get Asset URL
 * Automatically looks into public folder for assets
 */
function asset_url($path = '')
{
    $clean_path = ltrim($path, '/');

    // Smart Logic: Auto-detect if we need public/ in the path
    // If the current script URL contains /public/, then BASE_URL is the project root
    // and we need to add public/ to asset paths.
    // If the current script URL does NOT contain /public/, then public is the document root
    // and we should NOT add public/ to asset paths.

    $current_script = $_SERVER['SCRIPT_NAME'];
    $needs_public_prefix = (strpos($current_script, '/public/') !== false);

    if ($needs_public_prefix && strpos($clean_path, 'public/') !== 0) {
        // Local environment: BASE_URL is project root, need public/ prefix for assets/uploads
        return base_url('public/' . $clean_path);
    }

    return base_url($clean_path);
}

/**
 * Get User SMS Statistics
 * Returns array with total, sent, failed counts
 */
function get_user_sms_statistics($user_id)
{
    global $pdo;
    $stats = ['total_sms' => 0, 'sms_sent' => 0, 'sms_failed' => 0];

    try {
        // Total SMS
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM sms_logs WHERE user_id = ?");
        $stmt->execute([$user_id]);
        $stats['total_sms'] = (int) $stmt->fetchColumn();

        // SMS Sent (Case-insensitive check for robustness)
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM sms_logs WHERE user_id = ? AND LOWER(status) = 'sent'");
        $stmt->execute([$user_id]);
        $stats['sms_sent'] = (int) $stmt->fetchColumn();

        // SMS Failed (Case-insensitive check)
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM sms_logs WHERE user_id = ? AND LOWER(status) = 'failed'");
        $stmt->execute([$user_id]);
        $stats['sms_failed'] = (int) $stmt->fetchColumn();

    } catch (PDOException $e) {
        // Return 0s on error
    }

    return $stats;
}

/**
 * Get Active Contact Groups based on Role
 * Supports 'admin' (all) and 'user' (owned)
 */
function get_active_contact_groups($role, $user_id = null)
{
    global $pdo;
    $groups = [];
    try {
        if ($role === 'admin') {
            // Admin sees ALL active groups
            $stmt = $pdo->query("SELECT * FROM contact_groups WHERE status = 'active'");
            $groups = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } elseif ($role === 'user' && $user_id) {
            // User sees OWN active groups
            $stmt = $pdo->prepare("SELECT * FROM contact_groups WHERE owner_type = 'user' AND owner_id = ? AND status = 'active'");
            $stmt->execute([$user_id]);
            $groups = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    } catch (PDOException $e) {
        // Log error if needed
    }
    return $groups;
}

/**
 * Get SMS Delivery Statistics (System-wide for Admin)
 * Returns sent and failed counts
 */
function get_sms_delivery_stats()
{
    global $pdo;
    $stats = ['sent' => 0, 'failed' => 0, 'total' => 0];

    try {
        // Count sent SMS
        $sentStmt = $pdo->query("SELECT COUNT(*) as count FROM sms_logs WHERE status = 'sent'");
        $stats['sent'] = $sentStmt->fetch()['count'] ?? 0;

        // Count failed SMS
        $failedStmt = $pdo->query("SELECT COUNT(*) as count FROM sms_logs WHERE status = 'failed'");
        $stats['failed'] = $failedStmt->fetch()['count'] ?? 0;

        // Total
        $stats['total'] = $stats['sent'] + $stats['failed'];

    } catch (PDOException $e) {
        // Return zeros on error
    }

    return $stats;
}
?>