<?php
include realpath(dirname(__DIR__) . '/include/header.php');

// Get available subscription plans
try {
    $stmt = $conn->prepare("SELECT * FROM subscription_plans WHERE status = 'active' ORDER BY price ASC");
    $stmt->execute();
    $availablePlans = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $availablePlans = [];
}
try {
    $stmt =  $conn->prepare("
                SELECT setting_name, setting_value 
                FROM settings 
                WHERE setting_name IN ('currency_code', 'currency_symbol', 'currency_position')
            ");
    $stmt->execute();
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $settings = [];
    foreach ($results as $row) {
        $settings[$row['setting_name']] = $row['setting_value'];
    }
    // Set defaults if not found
    if (!isset($settings['currency_code'])) $settings['currency_code'] = 'USD';
    if (!isset($settings['currency_symbol'])) $settings['currency_symbol'] = '$';
    if (!isset($settings['currency_position'])) $settings['currency_position'] = 'before';
    $currentSettings = $settings;
} catch (Exception $e) {
    $currentSettings = [
        'currency_code' => 'USD',
        'currency_symbol' => '$',
        'currency_position' => 'before'
    ];
}

?>



<div class="col-xl-12">
    <div class="card">
        <div class="card-body">
            <h4 class="card-title">Create Account</h4>
            <p class="card-title-desc">Fill all information below to create a new account.</p>
            <div class="alert alert-info" role="alert">
                <strong>Note:</strong> The subdomain will be created automatically. Please enter a valid subdomain name.
            </div>
            <form class="needs-validation" action="?app_route=create_account_process" method="POST" id="ispForm" novalidate>
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="validationCustom01" class="form-label">ISP Wifi Name</label>
                            <input type="text" class="form-control" id="validationCustom01" placeholder="ISP Wifi Name" name="isp_name" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="validationCustom01" class="form-label">Username</label>
                            <input type="text" class="form-control" id="validationCustom01" placeholder="Username" name="username" required>
                        </div>
                    </div>

                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="validationCustom02" class="form-label">Email</label>
                            <input type="email" class="form-control" id="validationCustom02" placeholder="Email" name="email" required>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="validationCustom03" class="form-label">Phone Number</label>
                            <input type="text" class="form-control" id="validationCustom03" placeholder="Phone Number" name="phone" required>
                        </div>
                    </div>

                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="mb-3">
                            <label for="validationCustom06" class="form-label">Subdomain</label>
                            <div class="position-relative">
                                <input type="text" class="form-control" id="validationCustom06" placeholder="Subdomain" name="subdomain" required>
                                <span class="position-absolute end-0 top-50 translate-middle-y px-3 text-muted">
                                    .<?php echo MAIN_DOMAIN; ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Subscription Plan Selection -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="mb-3">
                            <label for="subscription_plan" class="form-label">Select Subscription Plan</label>
                            <select class="form-select" id="subscription_plan" name="subscription_plan_id" required>
                                <option value="">Choose a subscription plan...</option>
                                <?php foreach ($availablePlans as $plan): ?>
                                    <option value="<?= $plan['id'] ?>"
                                        data-price="<?= $plan['price'] ?>"
                                        data-duration="<?= $plan['duration_days'] ?>">
                                        <?= htmlspecialchars($plan['name']) ?> -
                                        <?= htmlspecialchars($currentSettings['currency_symbol']) . ' ' . number_format($plan['price'], 2) ?>/<?= $plan['duration_days'] ?> days

                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Plan Details Display -->
                <div class="row" id="planDetails" style="display: none;">
                    <div class="col-md-12">
                        <div class="card border-info">
                            <div class="card-header bg-light">
                                <h6 class="mb-0">Selected Plan Details</h6>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-3">
                                        <strong>Price:</strong> <?php echo htmlspecialchars($currentSettings['currency_symbol']) ?>
                                        <span id="planPrice">0.00</span>
                                    </div>
                                    <div class="col-md-3">
                                        <strong>Duration:</strong> <span id="planDuration">0</span> days
                                    </div>
                                    <div class="col-md-3">
                                        <strong>Expires:</strong> <span id="planExpiry">-</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>





                <div>
                    <button class="btn btn-primary" type="submit" name="create_account">Create Account</button>
                </div>
            </form>
        </div>
    </div>
    <!-- end card -->
</div>







<!-- Script -->
<script>
    // Plan selection handler
    document.getElementById('subscription_plan').addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        const planDetails = document.getElementById('planDetails');

        if (this.value) {
            const price = selectedOption.getAttribute('data-price');
            const duration = selectedOption.getAttribute('data-duration');


            document.getElementById('planPrice').textContent = parseFloat(price).toFixed(2);
            document.getElementById('planDuration').textContent = duration;
    

            // Calculate expiry date
            const startDate = new Date();
            const expiryDate = new Date(startDate.getTime() + (parseInt(duration) * 24 * 60 * 60 * 1000));
            document.getElementById('planExpiry').textContent = expiryDate.toLocaleDateString();

            // Update duration field
            document.getElementById('validationCustom05').value = duration;

            planDetails.style.display = 'block';
        } else {
            planDetails.style.display = 'none';
        }
    });

    document.getElementById('subdomain').addEventListener('input', function() {
        document.getElementById('subdomain_preview').innerText = this.value;
    });

    document.getElementById('ispForm').addEventListener('submit', function(event) {
        event.preventDefault();

        // Validate that a subscription plan is selected
        const planSelect = document.getElementById('subscription_plan');
        if (!planSelect.value) {
            Swal.fire({
                icon: 'error',
                title: 'Plan Required',
                text: 'Please select a subscription plan before creating the account.',
            });
            return;
        }

        // Submit the form
        this.submit();
    });
</script>

<?php
include realpath(dirname(__DIR__) . '/include/footer.php');
?>