<?php
require_once '../connection.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$input = json_decode(file_get_contents('php://input'), true);
$reference = $input['reference'];
$plan_id = $input['plan_id'];

// Verify payment with Paystack
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "https://api.paystack.co/transaction/verify/" . rawurlencode($reference),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer {$paystack_config['secret_key']}",
        "Cache-Control: no-cache"
    ]
]);

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

if ($err) {
    echo json_encode(['success' => false, 'message' => "CURL Error: $err"]);
    exit();
}

$result = json_decode($response, true);

if ($result['data']['status'] == 'success') {
    $amount = $result['data']['amount'] / 100;
    $metadata = $result['data']['metadata']['custom_fields'];
    
    // Extract metadata
    $client_id = null;
    $ip_address = null;
    $mac_address = null;
    
    foreach ($metadata as $field) {
        switch($field['variable_name']) {
            case 'client_id': $client_id = $field['value']; break;
            case 'ip_address': $ip_address = $field['value']; break;
            case 'mac_address': $mac_address = $field['value']; break;
        }
    }
    
    try {
        $pdo->beginTransaction();
        
        // Check if IP or MAC is already in use
        $stmt = $pdo->prepare("SELECT id FROM office_subscriptions WHERE (ip_address = ? OR mac_address = ?) AND status = 'active' AND end_date > NOW()");
        $stmt->execute([$ip_address, $mac_address]);
        if ($stmt->rowCount() > 0) {
            throw new Exception("IP or MAC address already has an active subscription");
        }
        
        // Get plan details
        $stmt = $pdo->prepare("SELECT * FROM office_subscription_plans WHERE id = ?");
        $stmt->execute([$plan_id]);
        $plan = $stmt->fetch();
        
        if (!$plan) {
            throw new Exception("Invalid plan");
        }
        
        // Calculate subscription dates
        $start_date = date('Y-m-d H:i:s');
        $end_date = date('Y-m-d H:i:s', strtotime("+{$plan['duration_days']} days"));
        
        // Create subscription
        $stmt = $pdo->prepare("
            INSERT INTO office_subscriptions (client_id, plan_id, mac_address, ip_address, start_date, end_date, paystack_reference, amount_paid, status) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active')
        ");
        $stmt->execute([$client_id, $plan_id, $mac_address, $ip_address, $start_date, $end_date, $reference, $amount]);
        $subscription_id = $pdo->lastInsertId();
        
        // Create IP-MAC binding
        $stmt = $pdo->prepare("
            INSERT INTO ip_mac_bindings (ip_address, mac_address, client_id, subscription_id, is_active) 
            VALUES (?, ?, ?, ?, 1)
            ON DUPLICATE KEY UPDATE 
            mac_address = VALUES(mac_address), 
            client_id = VALUES(client_id), 
            subscription_id = VALUES(subscription_id),
            is_active = 1,
            updated_at = NOW()
        ");
        $stmt->execute([$ip_address, $mac_address, $client_id, $subscription_id]);
        
        // Record Paystack transaction
        $stmt = $pdo->prepare("
            INSERT INTO paystack_transactions (reference, client_id, amount, status, paystack_response, subscription_id) 
            VALUES (?, ?, ?, 'success', ?, ?)
        ");
        $stmt->execute([$reference, $client_id, $amount, json_encode($result), $subscription_id]);
        
        // Configure MikroTik
        require_once 'mikrotik_api.php';
        $mikrotik_result = configureMikroTikInternetAccess($ip_address, $mac_address, $plan['bandwidth_mbps']);
        
        if (!$mikrotik_result['success']) {
            // Log error but don't rollback - subscription is still valid
            error_log("MikroTik configuration failed: " . $mikrotik_result['message']);
        }
        
        $pdo->commit();
        
        echo json_encode([
            'success' => true, 
            'message' => 'Subscription activated successfully',
            'mikrotik' => $mikrotik_result
        ]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Payment verification failed']);
}
?>