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

if (!isLoggedIn() || isAdmin()) {
    header('Location: login.php');
    exit();
}

$client_id = $_SESSION['user_id'];
$client_info = getClientNetworkInfo();

// Get client info
$stmt = $pdo->prepare("SELECT * FROM clients WHERE id = ?");
$stmt->execute([$client_id]);
$client = $stmt->fetch();

// Get active subscription
$stmt = $pdo->prepare("
    SELECT os.*, osp.name as plan_name, osp.type, osp.bandwidth_mbps 
    FROM office_subscriptions os
    JOIN office_subscription_plans osp ON os.plan_id = osp.id
    WHERE os.client_id = ? AND os.status = 'active' AND os.end_date > NOW()
    ORDER BY os.end_date DESC LIMIT 1
");
$stmt->execute([$client_id]);
$active_sub = $stmt->fetch();

// Get available plans
$stmt = $pdo->query("SELECT * FROM office_subscription_plans WHERE is_active = 1");
$plans = $stmt->fetchAll();

// Check if IP/MAC is already in use
$ip_in_use = false;
$mac_in_use = false;

if ($client_info['ip']) {
    $stmt = $pdo->prepare("SELECT * FROM office_subscriptions WHERE ip_address = ? AND status = 'active' AND end_date > NOW()");
    $stmt->execute([$client_info['ip']]);
    $ip_in_use = $stmt->rowCount() > 0;
}

if ($client_info['mac']) {
    $stmt = $pdo->prepare("SELECT * FROM office_subscriptions WHERE mac_address = ? AND status = 'active' AND end_date > NOW()");
    $stmt->execute([$client_info['mac']]);
    $mac_in_use = $stmt->rowCount() > 0;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Office Space Internet Subscription</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://js.paystack.co/v1/inline.js"></script>
</head>
<body>
    <nav class="navbar navbar-dark bg-dark">
        <div class="container-fluid">
            <span class="navbar-brand">Office Internet Subscription</span>
            <div>
                <span class="text-white me-3">Welcome, <?php echo htmlspecialchars($client['full_name']); ?></span>
                <a href="client/dashboard.php" class="btn btn-outline-light btn-sm">Back to Dashboard</a>
                <a href="logout.php" class="btn btn-outline-light btn-sm">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <?php if($active_sub): ?>
            <div class="alert alert-success">
                <h4>You have an active subscription!</h4>
                <p>Plan: <?php echo $active_sub['plan_name']; ?> (<?php echo $active_sub['bandwidth_mbps']; ?> Mbps)</p>
                <p>Valid until: <?php echo date('F j, Y H:i', strtotime($active_sub['end_date'])); ?></p>
                <p>Your IP: <?php echo $active_sub['ip_address']; ?></p>
                <p>Your MAC: <?php echo $active_sub['mac_address']; ?></p>
            </div>
        <?php endif; ?>

        <?php if($ip_in_use || $mac_in_use): ?>
            <div class="alert alert-warning">
                <strong>Note:</strong> Your device (IP: <?php echo $client_info['ip']; ?>, MAC: <?php echo $client_info['mac']; ?>) 
                <?php if($ip_in_use): ?>IP address is already in use with another active subscription.<?php endif; ?>
                <?php if($mac_in_use): ?>MAC address is already in use with another active subscription.<?php endif; ?>
            </div>
        <?php endif; ?>

        <div class="row">
            <?php foreach($plans as $plan): ?>
            <div class="col-md-4 mb-4">
                <div class="card h-100">
                    <div class="card-header bg-primary text-white text-center">
                        <h3><?php echo $plan['name']; ?></h3>
                    </div>
                    <div class="card-body text-center">
                        <h2 class="display-4">$<?php echo number_format($plan['price'], 2); ?></h2>
                        <p class="lead">
                            <?php 
                            switch($plan['type']) {
                                case 'daily': echo "24 Hours Access"; break;
                                case 'weekly': echo "7 Days Access"; break;
                                case 'monthly': echo "30 Days Access"; break;
                            }
                            ?>
                        </p>
                        <p>Speed: <?php echo $plan['bandwidth_mbps']; ?> Mbps</p>
                        <p>Dedicated IP & MAC Binding</p>
                        <button onclick="payWithPaystack(<?php echo $plan['id']; ?>, '<?php echo $plan['name']; ?>', <?php echo $plan['price']; ?>)" 
                                class="btn btn-success btn-lg w-100"
                                <?php echo ($active_sub || $ip_in_use || $mac_in_use) ? 'disabled' : ''; ?>>
                            Subscribe Now
                        </button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="card mt-4">
            <div class="card-header">
                <h5>Your Device Information</h5>
            </div>
            <div class="card-body">
                <table class="table">
                    <tr>
                        <th>IP Address:</th>
                        <td><code><?php echo htmlspecialchars($client_info['ip']); ?></code></td>
                    </tr>
                    <tr>
                        <th>MAC Address:</th>
                        <td><code><?php echo htmlspecialchars($client_info['mac'] ?: 'Not detected (please ensure you are on local network)'); ?></code></td>
                    </tr>
                </table>
                <?php if(!$client_info['mac']): ?>
                    <div class="alert alert-warning">
                        MAC address not detected. Please ensure you are connected to the local network.
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
    function payWithPaystack(planId, planName, amount) {
        let handler = PaystackPop.setup({
            key: '<?php echo $paystack_config['public_key']; ?>',
            email: '<?php echo $client['email']; ?>',
            amount: amount * 100, // Amount in kobo
            currency: 'GHS', // or your currency
            ref: 'OFFICE_' + Math.floor((Math.random() * 1000000000) + 1),
            metadata: {
                custom_fields: [
                    {
                        display_name: "Plan ID",
                        variable_name: "plan_id",
                        value: planId
                    },
                    {
                        display_name: "Client ID",
                        variable_name: "client_id",
                        value: <?php echo $client_id; ?>
                    },
                    {
                        display_name: "IP Address",
                        variable_name: "ip_address",
                        value: '<?php echo $client_info['ip']; ?>'
                    },
                    {
                        display_name: "MAC Address",
                        variable_name: "mac_address",
                        value: '<?php echo $client_info['mac']; ?>'
                    }
                ]
            },
            callback: function(response) {
                // Verify payment on your server
                verifyPayment(response.reference, planId);
            },
            onClose: function() {
                alert('Transaction cancelled');
            }
        });
        handler.openIframe();
    }

    function verifyPayment(reference, planId) {
        fetch('verify_payment.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                reference: reference,
                plan_id: planId
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Payment successful! Your subscription is active.');
                window.location.href = 'office_subscribe.php';
            } else {
                alert('Payment verification failed: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred. Please contact support.');
        });
    }
    </script>
</body>
</html>