<?php
// functions.php - Core business logic

require_once 'connection.php';

// Process subscription renewal
function renewSubscription($client_id, $plan_id, $payment_type = 'wallet') {
    global $pdo;
    
    try {
        $pdo->beginTransaction();
        
        // Get plan details
        $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ?");
        $stmt->execute([$plan_id]);
        $plan = $stmt->fetch();
        
        // Get client balance
        $stmt = $pdo->prepare("SELECT wallet_balance FROM clients WHERE id = ?");
        $stmt->execute([$client_id]);
        $client = $stmt->fetch();
        
        if($payment_type == 'wallet' && $client['wallet_balance'] < $plan['price']) {
            throw new Exception("Insufficient wallet balance");
        }
        
        // Calculate new dates
        $start_date = date('Y-m-d');
        $end_date = date('Y-m-d', strtotime("+{$plan['duration_days']} days"));
        
        // Deactivate old subscription
        $stmt = $pdo->prepare("UPDATE subscriptions SET is_active = 0 WHERE client_id = ? AND is_active = 1");
        $stmt->execute([$client_id]);
        
        // Create new subscription
        $stmt = $pdo->prepare("INSERT INTO subscriptions (client_id, plan_id, start_date, end_date) VALUES (?, ?, ?, ?)");
        $stmt->execute([$client_id, $plan_id, $start_date, $end_date]);
        $sub_id = $pdo->lastInsertId();
        
        // Process payment
        if($payment_type == 'wallet') {
            // Deduct from wallet
            $stmt = $pdo->prepare("UPDATE clients SET wallet_balance = wallet_balance - ? WHERE id = ?");
            $stmt->execute([$plan['price'], $client_id]);
            
            // Record transaction
            $ref = generateReference();
            $stmt = $pdo->prepare("INSERT INTO transactions (client_id, amount, type, reference, description) VALUES (?, ?, 'subscription_payment', ?, ?)");
            $stmt->execute([$client_id, $plan['price'], $ref, "Subscription renewed for {$plan['name']}"]);
        }
        
        // Record payment log
        $stmt = $pdo->prepare("INSERT INTO payment_logs (client_id, subscription_id, amount, payment_method, status) VALUES (?, ?, ?, ?, 'completed')");
        $stmt->execute([$client_id, $sub_id, $plan['price'], $payment_type]);
        
        // Update MikroTik PPPoE profile based on speed
        $mikrotik_profile = "plan_" . $plan['speed_mbps'] . "mbps";
        // Call MikroTik API to update user profile
        // updateMikroTikUser($client['pppoe_username'], $mikrotik_profile);
        
        $pdo->commit();
        return true;
        
    } catch(Exception $e) {
        $pdo->rollBack();
        error_log("Renewal failed: " . $e->getMessage());
        return false;
    }
}

// Auto-debit function (run via cron job daily)
function processAutoDebits() {
    global $pdo;
    
    // Find subscriptions expiring in next 3 days
    $stmt = $pdo->prepare("
        SELECT s.*, c.id as client_id, c.wallet_balance, c.auto_debit, p.price, p.name as plan_name, p.id as plan_id
        FROM subscriptions s
        JOIN clients c ON s.client_id = c.id
        JOIN plans p ON s.plan_id = p.id
        WHERE s.is_active = 1 
        AND s.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
        AND c.auto_debit = 1
        AND c.wallet_balance >= p.price
    ");
    $stmt->execute();
    $expiring_subs = $stmt->fetchAll();
    
    $processed = 0;
    foreach($expiring_subs as $sub) {
        if(renewSubscription($sub['client_id'], $sub['plan_id'], 'auto_debit')) {
            $processed++;
            
            // Record auto-debit transaction
            $ref = generateReference();
            $stmt = $pdo->prepare("INSERT INTO transactions (client_id, amount, type, reference, description) VALUES (?, ?, 'auto_debit', ?, 'Auto-debit subscription renewal')");
            $stmt->execute([$sub['client_id'], $sub['price'], $ref]);
        }
    }
    
    return $processed;
}

// Add funds to wallet
function addWalletFunds($client_id, $amount, $payment_method) {
    global $pdo;
    
    try {
        $pdo->beginTransaction();
        
        // Update wallet balance
        $stmt = $pdo->prepare("UPDATE clients SET wallet_balance = wallet_balance + ? WHERE id = ?");
        $stmt->execute([$amount, $client_id]);
        
        // Record transaction
        $ref = generateReference();
        $stmt = $pdo->prepare("INSERT INTO transactions (client_id, amount, type, reference, description, status) VALUES (?, ?, 'wallet_deposit', ?, ?, 'completed')");
        $stmt->execute([$client_id, $amount, $ref, "Wallet deposit via {$payment_method}"]);
        
        $pdo->commit();
        return true;
        
    } catch(Exception $e) {
        $pdo->rollBack();
        return false;
    }
}

// Check and warn expiring subscriptions (run via cron)
function sendExpiryWarnings() {
    global $pdo;
    
    $stmt = $pdo->prepare("
        SELECT s.*, c.email, c.full_name, p.name as plan_name
        FROM subscriptions s
        JOIN clients c ON s.client_id = c.id
        JOIN plans p ON s.plan_id = p.id
        WHERE s.is_active = 1 
        AND s.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
    ");
    $stmt->execute();
    $expiring = $stmt->fetchAll();
    
    foreach($expiring as $sub) {
        $days_left = (strtotime($sub['end_date']) - time()) / (60 * 60 * 24);
        // Send email notification
        $to = $sub['email'];
        $subject = "Subscription Expiry Warning";
        $message = "Dear {$sub['full_name']},\n\nYour {$sub['plan_name']} subscription will expire in " . ceil($days_left) . " days.\nPlease renew to continue using our service.\n\nThank you.";
        // mail($to, $subject, $message);
    }
}