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

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

$client_id = $_SESSION['user_id'];

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

// Get current subscription
$stmt = $pdo->prepare("
    SELECT s.*, p.name, p.speed_mbps, p.price 
    FROM subscriptions s 
    JOIN plans p ON s.plan_id = p.id 
    WHERE s.client_id = ? AND s.is_active = 1 AND s.end_date >= CURDATE()
    ORDER BY s.end_date DESC LIMIT 1
");
$stmt->execute([$client_id]);
$current_sub = $stmt->fetch();

// Get transaction history
$stmt = $pdo->prepare("SELECT * FROM transactions WHERE client_id = ? ORDER BY created_at DESC LIMIT 10");
$stmt->execute([$client_id]);
$transactions = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
    <title>ISP Manager - Client Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-dark bg-dark">
        <div class="container-fluid">
            <span class="navbar-brand">Welcome, <?php echo htmlspecialchars($client['full_name']); ?></span>
            <div>
                <span class="text-white me-3">Wallet: $<?php echo number_format($client['wallet_balance'], 2); ?></span>
                <a href="../logout.php" class="btn btn-outline-light btn-sm">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <?php if($current_sub): ?>
        <div class="alert alert-info">
            <h4>Current Subscription: <?php echo $current_sub['name']; ?> (<?php echo $current_sub['speed_mbps']; ?> Mbps)</h4>
            <p>Valid until: <?php echo date('F j, Y', strtotime($current_sub['end_date'])); ?></p>
            <?php 
            $days_left = (strtotime($current_sub['end_date']) - time()) / (60 * 60 * 24);
            if($days_left <= 7 && $days_left > 0):
            ?>
                <div class="alert alert-warning">Your subscription expires in <?php echo ceil($days_left); ?> days!</div>
            <?php elseif($days_left <= 0): ?>
                <div class="alert alert-danger">Your subscription has expired!</div>
            <?php endif; ?>
        </div>
        <?php else: ?>
        <div class="alert alert-danger">
            <h4>No Active Subscription</h4>
            <p>Please purchase a plan to continue using our service.</p>
        </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>Fund Wallet</h5>
                    </div>
                    <div class="card-body">
                        <form action="process_deposit.php" method="POST">
                            <div class="mb-3">
                                <label>Amount ($)</label>
                                <input type="number" name="amount" class="form-control" step="0.01" min="1" required>
                            </div>
                            <div class="mb-3">
                                <label>Payment Method</label>
                                <select name="payment_method" class="form-control" required>
                                    <option value="credit_card">Credit Card</option>
                                    <option value="bank_transfer">Bank Transfer</option>
                                    <option value="cash">Cash</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-success">Add Funds</button>
                        </form>
                    </div>
                </div>

                <div class="card mt-3">
                    <div class="card-header">
                        <h5>Auto-Debit Settings</h5>
                    </div>
                    <div class="card-body">
                        <form action="update_auto_debit.php" method="POST">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="auto_debit" id="auto_debit" 
                                       <?php echo $client['auto_debit'] ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="auto_debit">
                                    Automatically deduct subscription fee from wallet when due
                                </label>
                            </div>
                            <button type="submit" class="btn btn-primary mt-2">Update Settings</button>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>Available Plans</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <?php
                            $plans = $pdo->query("SELECT * FROM plans WHERE is_active = 1");
                            while($plan = $plans->fetch()):
                            ?>
                            <div class="col-md-4 mb-3">
                                <div class="card">
                                    <div class="card-body text-center">
                                        <h6><?php echo $plan['name']; ?></h6>
                                        <h4><?php echo $plan['speed_mbps']; ?> Mbps</h4>
                                        <p>$<?php echo $plan['price']; ?>/month</p>
                                        <form action="purchase_plan.php" method="POST">
                                            <input type="hidden" name="plan_id" value="<?php echo $plan['id']; ?>">
                                            <button type="submit" class="btn btn-primary btn-sm" 
                                                    <?php echo (!$current_sub || strtotime($current_sub['end_date']) < time()) ? '' : 'disabled'; ?>>
                                                Purchase
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        </div>
                    </div>
                </div>

                <div class="card mt-3">
                    <div class="card-header">
                        <h5>Transaction History</h5>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <thead>
                                <tr><th>Date</th><th>Type</th><th>Amount</th><th>Status</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach($transactions as $trans): ?>
                                <tr>
                                    <td><?php echo date('M d, Y', strtotime($trans['created_at'])); ?></td>
                                    <td><?php echo str_replace('_', ' ', ucfirst($trans['type'])); ?></td>
                                    <td>$<?php echo number_format($trans['amount'], 2); ?></td>
                                    <td><span class="badge bg-success"><?php echo $trans['status']; ?></span></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>