<?php
// includes/functions.php
require_once __DIR__ . '/db.php';

function is_logged_in() {
    return isset($_SESSION['user_id']);
}

function require_login() {
    if (!is_logged_in()) {
        redirect('login');
    }
}

function redirect($url) {
    // Auto-strip .php extension for clean URLs
    $url = preg_replace('/\.php(\?|$)/', '$1', $url);
    header("Location: $url");
    exit;
}

function generate_uuid() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
      mt_rand(0, 0xffff), mt_rand(0, 0xffff),
      mt_rand(0, 0xffff),
      mt_rand(0, 0x0fff) | 0x4000,
      mt_rand(0, 0x3fff) | 0x8000,
      mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}
function getTanzanianCarrier($phone) {
    if (empty($phone)) return 'Unknown';
    $phone = preg_replace('/[^0-9]/', '', $phone);
    if (strlen($phone) == 12 && substr($phone, 0, 3) == '255') {
        $phone = '0' . substr($phone, 3);
    }
    if (strlen($phone) >= 3) {
        $prefix = substr($phone, 0, 3);
        $vodacom = ['074', '075', '076', '072'];
        $tigo = ['065', '067', '071'];
        $airtel = ['068', '069', '078'];
        $halotel = ['061', '062'];
        $zantel = ['077'];
        $ttcl = ['073'];
        
        if (in_array($prefix, $vodacom)) return 'Vodacom';
        if (in_array($prefix, $tigo)) return 'Tigo';
        if (in_array($prefix, $airtel)) return 'Airtel';
        if (in_array($prefix, $halotel)) return 'Halotel';
        if (in_array($prefix, $zantel)) return 'Zantel';
        if (in_array($prefix, $ttcl)) return 'TTCL';
    }
    return 'Unknown';
}

function get_site_settings(PDO $pdo): array {
    try {
        $stmt = $pdo->query("SELECT * FROM site_settings WHERE id = 1 LIMIT 1");
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) return $row;
    } catch (PDOException $e) {}
    // Defaults if table missing / empty
    return [
        'site_name'     => 'Kindamba Pay',
        'site_logo'     => 'assets/images/logo.png',
        'site_favicon'  => 'assets/images/favicon.png',
        'landing_title' => 'UTAMU',
        'footer_copy'   => 'Kindamba Pay Dashboard. All Rights Reserved.',
        'footer_made_by' => 'Kindamba Pay Dev',
        'allow_registration' => 1,
        'system_commission' => 0.00,
        'min_withdrawal' => 1000.00
    ];
}

function track_visit($pdo, $domain_id, $event_type = 'view') {
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    if ($ip === '::1') $ip = '127.0.0.1';
    
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    // Simple device detection
    $device = 'Desktop';
    if (preg_match('/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i', $ua)) {
        $device = 'Tablet';
    } elseif (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile)/i', $ua)) {
        $device = 'Mobile';
    }
    
    $isp = 'Unknown';
    $region = 'Unknown';
    
    if ($ip !== '127.0.0.1' && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
        try {
            $ctx = stream_context_create(['http' => ['timeout' => 2]]);
            $geo = @file_get_contents("http://ip-api.com/json/{$ip}?fields=status,regionName,isp", false, $ctx);
            if ($geo) {
                $data = json_decode($geo, true);
                if (($data['status'] ?? '') === 'success') {
                    $isp = $data['isp'] ?? 'Unknown';
                    $region = $data['regionName'] ?? 'Unknown';
                }
            }
        } catch (Exception $e) {}
    }
    
    try {
        $stmt = $pdo->prepare("INSERT INTO link_analytics (domain_id, ip_address, user_agent, isp, region, device, event_type) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$domain_id, $ip, $ua, $isp, $region, $device, $event_type]);
    } catch (PDOException $e) {}
}

/**
 * Sends SMS via NextSMS (nextsms.co.tz)
 * @param string $to Recipient phone number (e.g. 255712345678)
 * @param string $message The SMS message
 * @return bool Success or failure
 */
function send_nextsms($to, $message) {
    if (!defined('NEXTSMS_USERNAME') || !defined('NEXTSMS_PASSWORD')) return false;
    
    // Ensure phone starts with 255
    $to = preg_replace('/[^0-9]/', '', $to);
    if (strlen($to) == 10 && substr($to, 0, 1) == '0') {
        $to = '255' . substr($to, 1);
    }

    $payload = [
        'from' => defined('NEXTSMS_SENDER_ID') ? NEXTSMS_SENDER_ID : 'NEXTSMS',
        'to'   => $to,
        'text' => $message
    ];

    $ch = curl_init('https://messaging-service.co.tz/api/sms/v1/text/single');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Basic ' . base64_encode(NEXTSMS_USERNAME . ':' . NEXTSMS_PASSWORD),
            'Content-Type: application/json',
            'Accept: application/json'
        ],
        CURLOPT_SSL_VERIFYPEER => true
    ]);

    $res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($code >= 200 && $code < 300) {
        return true;
    }
    
    error_log("[NextSMS] Failed sending to $to. Code: $code. Res: $res");
    return false;
}
?>

