@php use Carbon\Carbon; @endphp
@extends('layouts.app')

@section('content')
<meta name="csrf-token" content="{{ csrf_token() }}">
<style>
    :root {
        --primary-teal: #0E4F66;
        --sidebar-teal: #0B3F52;
        --accent-gold: #C9A23F;
        --light-bg: #F4F6F9;
    }


    .plan-card {
        border: none;
        border-radius: 12px;
        transition: all 0.3s ease;
    }

    .plan-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 25px rgba(0,0,0,0.08);
    }

    .plan-header {
        background: var(--primary-teal);
        color: #fff;
        border-radius: 12px 12px 0 0;
        padding: 25px;
    }

    .plan-popular {
        background: var(--accent-gold);
        color: #000;
        font-weight: 600;
        padding: 5px 15px;
        border-radius: 50px;
        font-size: 12px;
        display: inline-block;
        margin-bottom: 10px;
    }

    .plan-price {
        font-size: 32px;
        font-weight: 700;
    }

    .plan-features li {
        padding: 6px 0;
        font-size: 14px;
    }

    .btn-theme {
        background: var(--primary-teal);
        color: #fff;
        border-radius: 6px;
        font-weight: 500;
    }

    .btn-theme:hover {
        background: var(--sidebar-teal);
        color: #fff;
    }

    .btn-outline-theme {
        border: 2px solid var(--primary-teal);
        color: var(--primary-teal);
        font-weight: 500;
    }

    .btn-outline-theme:hover {
        background: var(--primary-teal);
        color: #fff;
    }

    .dropdown-menu.dropdown-menu-end.navbar-dropdown.preview-list.show {
        right: 0;
    }
</style>

<div class="container-fluid">
    <div class="inside-body-campus">
        <div class="col-12">
            <div class="card">
                <div class="card-header py-3">
                    <div class="text-center ">
                     <h4 class="mb-2">Subscription Plans</h4>
                     <p class="text-muted m-0">Choose a plan that fits your hosting needs</p>
                   </div>
                </div>
                <div class="card-body">
                  <div class="subscription-section">
                    <div class="toast-container position-fixed top-0 end-0 p-3">
                        <div id="liveToast" class="toast align-items-center text-bg-success border-0">
                            <div class="d-flex">
                            <div class="toast-body" id="toastMessage"></div>
                            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                            </div>
                        </div>
                    </div>

                    @if($hasSubscription)

                    @php
                        $currentPriceId = $subscription->stripe_price;
                    @endphp

                    <div class="card mb-4 shadow-sm">
                        <div class="card-header bg-light">
                            <h5 class="mb-0">Active Subscription</h5>
                        </div>

                        <div class="card-body">

                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>Subscription ID:</strong> {{ $subscription->stripe_id }}</p>

                                    <p>
                                        <strong>Status:</strong>
                                        <span class="badge 
                                            {{ $stripeSubscription->status === 'active' ? 'bg-success' : 'bg-danger' }}">
                                            {{ ucfirst($stripeSubscription->status) }}
                                        </span>
                                    </p>

                                    
                                </div>
                                
                                <div class="col-md-6">
                                    @php 
                                        $stripeSubscription = $subscription->asStripeSubscription();
                                        $currentPeriodStart = $stripeSubscription->items->data[0]->current_period_start ?? null;
                                        $currentPeriodEnd   = $stripeSubscription->items->data[0]->current_period_end ?? null;
                                    @endphp
                                    <p>
                                        <strong>Started:</strong><br>
                                        {{ \Carbon\Carbon::createFromTimestamp($currentPeriodStart)->format('F d, Y h:i A') }}
                                    </p>
                                    @if(!$stripeSubscription->cancel_at_period_end)
                                        <p>
                                            <strong>Next Renewal:</strong><br>
                                            {{ \Carbon\Carbon::createFromTimestamp($currentPeriodEnd)->format('F d, Y h:i A') }}
                                        </p>
                                    @endif

                                    @if($stripeSubscription->cancel_at_period_end)
                                        <p class="text-warning">
                                            Subscription will cancel on 
                                            {{ \Carbon\Carbon::createFromTimestamp($currentPeriodEnd)->format('F d, Y h:i A') }}
                                        </p>
                                    @endif

                                    {{-- <a target="_blank" href="{{$invoices}}" class="btn btn-info btn-sm" >Download Invioce </a> --}}
                                </div>
                            </div>
                            <div class="d-flex gap-2">
                                <a href="{{route('host.subscriptions.details',$subscription->id)}}" class="btn btn-info btn-sm" >View Payment History</a>

                                {{-- Cancel Button --}}
                                @if(!$stripeSubscription->cancel_at_period_end && $stripeSubscription->status === 'active')
                                    <form id="cancelSubscriptionForm" method="POST" action="{{route('cancel.subscription')}}">
                                        @csrf
                                        <button class="btn btn-danger btn-sm">
                                            Cancel Subscription
                                        </button>
                                    </form>
                                @endif
                            </div>

                        </div>
                    </div>

                    @endif
                
                    <div class="row g-4">
                        
                
                        @foreach($plans as $plan)
                        <div class="col-md-4">
                            <div class="card plan-card shadow-sm h-100">
                
                                <div class="plan-header text-center">
                                    @if($plan->is_popular)
                                        <span class="plan-popular">Most Popular</span>
                                    @endif
                
                                    <h5 class="fw-bold">{{ $plan->name }}</h5>
                                    <p class="small mb-2">{{ $plan->description }}</p>
                
                                    <div class="plan-price">
                                        ${{ number_format($plan->price_monthly, 2) }}
                                        <small class="fs-6">/month</small>
                                    </div>
                
                                    @if($plan->trial_days > 0)
                                        <div class="mt-2">
                                            <span class="badge bg-success">
                                                {{ $plan->trial_days }} Days Free Trial
                                            </span>
                                        </div>
                                    @endif
                                </div>
                
                                <div class="card-body d-flex flex-column">
                
                                    <ul class="list-unstyled plan-features mb-4">
                                        @php
                                            $features = is_array($plan->features)
                                                ? $plan->features
                                                : json_decode($plan->features, true);
                                        @endphp
                
                                        @foreach($features as $feature)
                                            <li> <i class="mdi mdi-check-circle fs-5 menu-icon text-success"></i> {{ $feature }}</li>
                                        @endforeach
                                    </ul>
                
                                    @php
                                        $currentPriceId = $hasSubscription ? $subscription->stripe_price : null;
                                        $trialUsed = auth()->user()->trial_used ?? false;
                                    @endphp

                                    <div class="mt-auto d-grid">

                                    @if($hasSubscription && $currentPriceId === $plan->stripe_price_id_monthly)

                                        <button class="btn btn-success" disabled>
                                            Current Plan
                                        </button>

                                    @elseif($hasSubscription)

                                        @if($plan->price_monthly > $currentAmount)
                                            <button class="btn btn-warning currentPlan"
                                                data-price-id="{{ $plan->stripe_price_id_monthly }}"
                                                data-bs-toggle="modal"
                                                data-bs-target="#paymentModal"
                                                >
                                                Upgrade Plan
                                            </button>
                                        @else
                                            @if($plan->price_monthly == 0 && $trialUsed)

                                                <button class="btn btn-secondary" disabled>
                                                    Trial Already Used
                                                </button>

                                            @else
                                                <button class="btn btn-info currentPlan"
                                                    data-price-id="{{ $plan->stripe_price_id_monthly }}"
                                                    data-bs-toggle="modal"
                                                    data-bs-target="#paymentModal"
                                                    >
                                                    Downgrade Plan
                                                </button>
                                            @endif
                                        @endif

                                    @else

                                        {{-- Hide trial plan if already used --}}
                                        @if($plan->price_monthly == 0 && $trialUsed)

                                            <button class="btn btn-secondary" disabled>
                                                Trial Already Used
                                            </button>

                                        @else

                                            <button class="btn {{ $plan->is_popular ? 'btn-theme' : 'btn-outline-theme' }} currentPlan"
                                                data-price-id="{{ $plan->stripe_price_id_monthly }}"
                                                data-bs-toggle="modal"
                                                data-bs-target="#paymentModal">
                                                {{ $plan->price_monthly == 0 ? 'Start Free Trial' : 'Choose Plan' }}
                                            </button>

                                        @endif

                                    @endif

                                    </div>
                
                                </div>
                
                            </div>
                        </div>
                        @endforeach
                
                    </div>
                        
                  </div>
                </div>

            </div>
        </div>
    </div>
</div>



<div class="modal fade" id="paymentModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content shadow-lg">

      <div class="modal-header">
        <h5 class="modal-title">Complete Your Subscription</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body">

        <div class="alert alert-danger d-none" id="card-errors"></div>

        <form id="payment-form">

          <!-- Billing Name -->
          <div class="mb-3">
            <label class="form-label">Full Name</label>
            <input type="text"
                   id="billing_name"
                   class="form-control"
                   placeholder="John Doe"
                   value="{{auth()->user()->name}}"
                   required>
          </div>

          <!-- Address Line -->
          <div class="mb-3">
            <label class="form-label">Address Line 1</label>
            <input type="text"
                   id="billing_line1"
                   class="form-control"
                   placeholder="Street address"
                   required>
          </div>

          <!-- City + Postal -->
          <div class="row">
            <div class="col-md-12 mb-3">
              <label class="form-label">City</label>
              <input type="text"
                     id="billing_city"
                     class="form-control"
                     required>
            </div>
          </div>

          <!-- Country -->
          <div class="mb-3">
            <label class="form-label">Country</label>
            <input type="text"
                   id="billing_country"
                   class="form-control"
                   value="IN"
                   readonly>
          </div>

          <!-- Card Element -->
          <div class="mb-3">
            <label class="form-label">Card Details</label>
            <div id="card-element" class="form-control p-3"></div>
          </div>

          <input type="hidden" name="price_id" id="price_id" value="">

          <button id="submitBtn" type="submit" class="btn btn-primary w-100">
            <span id="btnText">Pay</span>
            <span id="spinner" class="spinner-border spinner-border-sm d-none"></span>
          </button>

        </form>

      </div>

    </div>
  </div>
</div>


<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!-- Stripe -->
<script src="https://js.stripe.com/v3/"></script>

<!-- Bootstrap -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

    const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    axios.defaults.headers.common['X-CSRF-TOKEN'] = token;
    var url ="{{route('subscribe')}}";

    $(document).on('click', '.currentPlan', function () {

        let priceId = $(this).data('price-id');

        // Set into hidden input
        $('#price_id').val(priceId);

    });

</script>

<script>

const stripe = Stripe("pk_test_51PIlyJSIEXIA1SQjDioPSwUgK7nRgyiSlIAtPar2omwyheZ7GwYMJuVbRKyUzr5vfIfDFD1xTRG7vJqlPW8R4LtN00ivDWvxq4");
const elements = stripe.elements();

const card = elements.create("card", {
    style: {
        base: {
            fontSize: "16px",
            color: "#212529"
        }
    }
});

card.mount("#card-element");

const form = document.getElementById("payment-form");
const submitBtn = document.getElementById("submitBtn");
const btnText = document.getElementById("btnText");
const spinner = document.getElementById("spinner");
const errorBox = document.getElementById("card-errors");
const modalElement = document.getElementById("paymentModal");
const bootstrapModal = bootstrap.Modal.getOrCreateInstance(modalElement);

card.on("change", function (event) {
    if (event.error) {
        errorBox.textContent = event.error.message;
        errorBox.classList.remove("d-none");
    } else {
        errorBox.classList.add("d-none");
    }
});

form.addEventListener("submit", async function (e) {
    e.preventDefault();

    submitBtn.disabled = true;
    btnText.classList.add("d-none");
    spinner.classList.remove("d-none");
    errorBox.classList.add("d-none");

    var priceID = $('#price_id').val();

    const name = document.getElementById("billing_name").value;
    const line1 = document.getElementById("billing_line1").value;
    const city = document.getElementById("billing_city").value;
    const country = document.getElementById("billing_country").value;

    try {

        // 1️⃣ Create Payment Method
        const { paymentMethod, error } = await stripe.createPaymentMethod({
            type: "card",
            card: card,
            billing_details: {
                name: name,
                address: {
                    line1: line1,
                    city: city,
                    country: country,
                }
            }
        });

        if (error) throw error;

        // 2️⃣ Send to Backend
        const response = await axios.post(url, {
            payment_method: paymentMethod.id,
            priceID: priceID,
            name: name,
            line1: line1,
            city: city,
            country: country,
        });

        console.log(response.data);

        // 3️⃣ Handle Backend Error
        if (response.data.status === "error") {
            throw new Error(response.data.message);
        }

        // 4️⃣ Handle 3D Secure
        if (response.data.status === "requires_action") {

            const result = await stripe.confirmCardPayment(
                response.data.client_secret
            );

            if (result.error) {
                throw result.error;
            }

            showToast("Subscription activated successfully.", "success");
            bootstrapModal.hide();
            setTimeout(() => window.location.reload(), 1500);
            return;
        }

        // 5️⃣ Success case
        if (response.data.status === "success") {
            showToast(response.data.message || "Subscription activated successfully.", "success");
            bootstrapModal.hide();
            setTimeout(() => window.location.reload(), 1500);
        }

    } catch (err) {

        console.error(err);

        errorBox.textContent =
            err.response?.data?.message ||
            err.message ||
            "Payment failed. Please try again.";

        errorBox.classList.remove("d-none");
    }

    submitBtn.disabled = false;
    btnText.classList.remove("d-none");
    spinner.classList.add("d-none");
});


function showToast(message, type = "success") {
    const toastEl = document.getElementById("liveToast");
    const toastMsg = document.getElementById("toastMessage");

    toastEl.classList.remove("text-bg-success", "text-bg-danger");
    toastEl.classList.add(type === "success" ? "text-bg-success" : "text-bg-danger");

    toastMsg.textContent = message;

    const toast = new bootstrap.Toast(toastEl);
    toast.show();
}
</script>


<script>
$(document).ready(function () {

    $('#cancelSubscriptionBtn').on('click', function (e) {
        e.preventDefault();

        Swal.fire({
            title: 'Are you sure?',
            text: "Your subscription will be cancelled at period end.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, cancel it!'
        }).then((result) => {

            if (result.isConfirmed) {

                $.ajax({
                    url: $('#cancelSubscriptionForm').attr('action'),
                    type: 'POST',
                    data: $('#cancelSubscriptionForm').serialize(),
                    success: function (response) {

                        Swal.fire({
                            icon: 'success',
                            title: 'Cancelled!',
                            text: response.message,
                            timer: 2000,
                            showConfirmButton: false
                        });

                        setTimeout(function () {
                            location.reload();
                        }, 2000);
                    },
                    error: function (xhr) {

                        Swal.fire({
                            icon: 'error',
                            title: 'Error!',
                            text: 'Something went wrong. Please try again.'
                        });
                    }
                });

            }

        });
    });

});

function toggleDropdown(element) {
    let menu = $(element).next('.preview-list');

    // toggle show class on button
    $(element).toggleClass('show');

    // toggle show class on dropdown
    menu.toggleClass('show');
}

// click event
$(document).on('click', '.dropdown-toggle', function(e){
    e.preventDefault();
    toggleDropdown(this);
});

$(document).on('click', function(e){
    if(!$(e.target).closest('.dropdown-toggle, .preview-list').length){
        $('.dropdown-toggle').removeClass('show');
        $('.preview-list').removeClass('show');
    }
});
</script>
@endsection