<?php
// Include necessary files and configurations
session_start();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$user_id = $_SESSION['user_id'] ?? null;
$company_id = $_SESSION['company_id'] ?? null;

include('includes/dbconn.php'); // Database connection script

// Redirect or handle the case where there is no user_id in the session
if ($user_id === null) {
    // Redirect to login page or show an error message
    header("Location: login.php");
    exit;
}


// Function to check subscription status
function checkSubscriptionStatus($userId, $conn) {
    $today = date("Y-m-d");
    $query = "SELECT end_date FROM subscriptions WHERE user_id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $end_date = $row['end_date'];
        $end_date_plus_grace = date('Y-m-d', strtotime($end_date. ' + 2 days'));

        if ($today <= $end_date) {
            return 'active';
        } elseif ($today <= $end_date_plus_grace) {
            return 'grace';
        } else {
            return 'expired';
        }
    } else {
        return 'no_subscription';
    }
}

// Fetch subscription types and their details from the database
$subscriptionTypesQuery = "SELECT type_id, type_name, amount, type_details FROM subscription_types";
$subscriptionTypesResult = $conn->query($subscriptionTypesQuery);
$subscriptionTypes = [];
while ($type = $subscriptionTypesResult->fetch_assoc()) {
    $subscriptionTypes[$type['type_id']] = $type;
}

// Check the user's subscription status
$userSubscriptionStatus = checkSubscriptionStatus($_SESSION['user_id'], $conn);

// Redirect to payment page if subscription is expired
if ($userSubscriptionStatus === 'expired') {
    header("Location: payment_page.php"); // Replace with your payment page URL
    exit;
}

// Rest of your HTML and PHP code
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php
    $title = "Add Subcription Payment";
    include 'partials/title-meta.php';
    ?>
    
    <link href="assets/libs/mohithg-switchery/switchery.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/multiselect/css/multi-select.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/selectize/css/selectize.bootstrap3.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/bootstrap-touchspin/jquery.bootstrap-touchspin.min.css" rel="stylesheet" type="text/css" />
        <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />

    <?php
    include 'partials/head-css.php';
    ?>
</head>

<body>
    <?php
    include 'partials/body.php';
    ?>

    <div id="wrapper">
        <?php
        $pagetitle = "Add Subcription Payment";
        include 'partials/menu.php';
        ?>

        <div class="content-page">
            <div class="content">
                <div class="container-fluid">
                    <!-- Content Here -->
                    <?php if ($userSubscriptionStatus === 'grace') : ?>
                        <div class="alert alert-warning">
                            Your subscription is in its grace period. Please renew soon.
                        </div>
                    <?php endif; ?>

                    <!-- Payment Form -->
                    <div class="card">
                        <div class="card-body">
                            <h4 class="header-title">Renew Subscription</h4>

                            <form id="paymentForm" action="process_payment.php" method="post">
                                <!-- User ID (Hidden) -->
                                <input type="hidden" name="user_id" value="<?php echo htmlspecialchars($user['user_id']); ?>">
                                
                                <div class="col-lg-6">
                                    <!-- Subscription Amount (Automatically filled based on chosen plan) -->
                                    <div class="mb-3">
                                        <label for="amount">Subscription Amount:</label>
                                        <input type="number" class="form-control" id="amount" name="amount" step="0.01" readonly>
                                    </div>
                            
                                    <!-- Start Date (Read-Only) -->
                                    <div class="mb-3">
                                        <label for="start_date">Start Date:</label>
                                        <input type="date" class="form-control" id="start_date" name="start_date" readonly value="<?php echo date('Y-m-d'); ?>">
                                    </div>
                            
                                    <!-- Subscription Plan Type -->
                                    <div class="mb-3">
                                        <label for="subscription_plan_type">Subscription Plan:</label>
                                        <select class="form-control" id="subscription_plan_type" name="subscription_plan_type" data-toggle="select2" required>
                                            <option value="" selected>Please select your subscription</option>
                                            <?php foreach ($subscriptionTypes as $typeId => $typeDetails): ?>
                                                <option value="<?php echo $typeId; ?>" data-amount="<?php echo $typeDetails['amount']; ?>">
                                                    <?php echo htmlspecialchars($typeDetails['type_name']) . " - $" . htmlspecialchars($typeDetails['amount']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                            
                                    <!-- Payment Processor Selection -->
                                    <div class="mb-3">
                                        <label for="payment_processor">Payment Processor:</label>
                                        <select class="form-control" id="payment_processor" name="payment_processor" data-toggle="select2" required>
                                            <option value="">Select Payment Method</option>
                                            <option value="paypal">PayPal</option>
                                            <option value="card">Credit/Debit Card</option>
                                            <option value="clover">Clover</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <br>
                                <!-- Dynamic Pay Button -->
                                <button type="submit" id="payButton" class="btn btn-primary">Pay</button>
                            </form>
                        </div> <!-- end card-body-->
                    </div> <!-- end card-->

                </div> <!-- container -->
            </div> <!-- content -->
            <?php include 'partials/footer.php'; ?>
        </div>

        <!-- ... rest of your script ... -->
    </div>
    <!-- END wrapper -->

    
<?php
include 'partials/right-sidebar.php';
?>

<?php
include 'partials/footer-scripts.php';
?>

<!-- Plugin js-->
<script src="assets/libs/parsleyjs/parsley.min.js"></script>

<!-- Validation init js-->
<script src="assets/js/pages/form-validation.init.js"></script>

<!-- App js -->
<script src="assets/js/app.min.js"></script>
<script src="assets/libs/selectize/js/standalone/selectize.min.js"></script>
<script src="assets/libs/mohithg-switchery/switchery.min.js"></script>
<script src="assets/libs/multiselect/js/jquery.multi-select.js"></script>
<script src="assets/libs/select2/js/select2.min.js"></script>
<script src="assets/libs/jquery-mockjax/jquery.mockjax.min.js"></script>
<script src="assets/libs/devbridge-autocomplete/jquery.autocomplete.min.js"></script>
<script src="assets/libs/bootstrap-touchspin/jquery.bootstrap-touchspin.min.js"></script>
<script src="assets/libs/bootstrap-maxlength/bootstrap-maxlength.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('payment_processor').onchange = function() {
        document.getElementById('payButton').textContent = 'Pay with ' + this.options[this.selectedIndex].text;
    };
});
</script>

<script>
        document.getElementById('subscription_plan_type').addEventListener('change', function() {
            var selectedOption = this.options[this.selectedIndex];
            var amount = selectedOption.getAttribute('data-amount');
            document.getElementById('amount').value = amount;
        });
</script>

<script>
    $(document).ready(function() {
        $('#client_name').select2();
    });
</script>
<script>
    $(document).ready(function() {
        $('#payment_processor').select2();
    });
</script>
<script>
    $(document).ready(function() {
        $('#subscription_plan_type').select2();
    });
</script>
<script>
function calculateTotal() {
    var quantity = document.getElementById('quantity').value;
    var unitPrice = document.getElementById('unit_price').value;
    var total = quantity * unitPrice;
    
    document.getElementById('total_amount').value = total.toFixed(2); // Set total amount with two decimal places
}
</script>

<script>
    // Get today's date
    var today = new Date();

    // Format it as YYYY-MM-DD (which is the format commonly used in databases)
    var formattedDate = today.toISOString().substr(0, 10);

    // Set the default value of the input field to today's date
    document.getElementById("start_date").value = formattedDate;
</script>
</body>
</html>
