@extends('Admin.layouts.master')
@section('content')
    @php
        $currentPage = 'dashboard';
    @endphp
    <div class="layout-px-spacing">
        <div class="middle-content container-xxl p-0">
            <div class="row layout-top-spacing ">
                <div class="top-tabel">
                    <div class="row">
                        <div class="col-md-4">
                            <h6 class="card-title">Dashboard</h6>
                        </div>
                    </div>
                </div>
                <div class="col-12 d-flex align-items-center gap-3 p-0 mb-4">

                    <div class="col-6">
                        <div class="card">
                            <div class="card-body">
                                @if (!$customReferralCode)
                                    <form id="create_custom_referral_code" enctype="multipart/form-data">
                                        {{ csrf_field() }}
                                        <h5>Create Custom Referral Code:-

                                            <input type="text" class="form-control" name="referral_code"
                                                id="referral_code" value="" placeholder="Enter Referral Code"
                                                oninput="this.value = this.value.toUpperCase().replace(/\s/g, '')"
                                                maxlength="15">
                                            <div class="">
                                                <button id="create_custom_code" type="submit"
                                                    class="download-btn-custom mt-3 custom-width-10">Submit</button>
                                            </div>


                                    </form>
                                @endif
                                @if ($customReferralCode && $customReferralCode->referral_code)
                                    <form id="create_custom_referral_code" enctype="multipart/form-data">
                                        {{ csrf_field() }}
                                        <h5>My Custom Referral Code:-</h5>

                                        <input type="text" class="form-control" name="referral_code" id="referral_code"
                                            value="{{ $customReferralCode->referral_code }}"
                                            placeholder="Enter Referral Code"
                                            oninput="this.value = this.value.toUpperCase().replace(/\s/g, '')"
                                            maxlength="15">
                                        <input type="hidden" name="id" value="{{ $customReferralCode->id }}" />
                                        <div class="d-flex" style="justify-content: space-between;">
                                            <button id="create_custom_code" type="submit"
                                                class="download-btn-custom mt-3 custom-width-10">Update</button>
                                            {{-- <button id="create_custom_code" type="submit" class="download-btn-cancel mt-3 custom-width-10">Deactivate Code</button> --}}

                                        </div>


                                    </form>
                                @endif
                            </div>
                        </div>
                    </div>


                </div>
                <div class="col-12 d-flex align-items-center gap-3 p-0 mb-4">
                    <div class="col-6">
                        <div class="card">
                            <div class="card-body">
                                <a href="{{ route('manage.customer') }}">
                                    <h5>No of Customers</h5>
                                    <h2 class="m-0 font-weight-bold">{{ $customerCount }}</h2>
                                </a>
                            </div>
                        </div>
                    </div>
                    {{-- <div class="col-6">
                        <div class="card">
                            <div class="card-body">
                                <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
                                    <ol class="carousel-indicators m-0">
                                        <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
                                        <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
                                        <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
                                    </ol>
                                    <div class="carousel-inner">
                                        <div class="carousel-item active">
                                            <h5>Passports Live Now</h5>
                                            <h2 class="m-0 font-weight-bold">Cheers to Summer</h2>
                                        </div>
                                        <div class="carousel-item">
                                            <h5>Passports Live Now</h5>
                                            <h2 class="m-0 font-weight-bold">Cheers to Summer</h2>
                                        </div>
                                        <div class="carousel-item">
                                            <h5>Passports Live Now</h5>
                                            <h2 class="m-0 font-weight-bold">Cheers to Summer</h2>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </div> --}}
                    <div class="col-6">
                        <div class="card">
                            <div class="card-body">
                                <a href="{{ route('manage.restaurants') }}">
                                    <h5>No of Restaurants</h5>
                                    <h2 class="m-0 font-weight-bold">{{ $restaurantCount }}</h2>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-12 d-flex align-items-center p-0 mb-4">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h5>User Graph</h5>
                                    <select class="form-control w-25" id="graph-filter">
                                        <option value="monthly" selected>Monthly</option>
                                        <option value="quarterly">Quarterly</option>
                                        <option value="yearly">Yearly</option>
                                    </select>
                                </div>
                                <div id="user-chart"></div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <h5>Sales Graph</h5>
                                    <select class="form-control w-50" id="sales-chart-options">
                                        <option value="monthly" selected>Monthly</option>
                                        <option value="quarterly">Quarterly</option>
                                        <option value="yearly">Yearly</option>
                                        <option value="daily">Last 7 Days</option>
                                    </select>
                                </div>
                                <div id="sales-chart"></div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
            <div class="col-12 d-flex align-items-center p-0 mb-4">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-body">
                            <h5>Recent Transactions</h5>
                            <form action="{{ route('export.recent.transactions') }}" method="POST" id="customer-form">
                                @csrf
                                <input type="hidden" name="selected_id" id="ids" disabled>
                                <input type="hidden" name="all_id" id="all_id" value="all" disabled>
                                <div class="d-flex justify-content-between align-items-center mb-3">
                                    <table id="zero-config" class="table dt-table-hover location_table" style="width:100%">
                                        <thead class="text-center">
                                            <tr>
                                                <th class="w-10px pe-2">
                                                    <div
                                                        class="form-check form-check-sm form-check-custom form-check-solid me-3">
                                                        <input class="form-check-input" type="checkbox" name="customer_ids"
                                                            id="select-all-ids" />
                                                    </div>
                                                </th>
                                                <th class="text-start">Sr no</th>
                                                <th class="text-start">Name</th>
                                                <th class="text-start">Customer Id</th>
                                                <th class="text-start">Amount</th>
                                                <th class="text-start">Status</th>
                                                <th class="text-start">payment Details</th>
                                            </tr>
                                        </thead>
                                        <tbody class="text-center">
                                            @foreach ($formatted_transactions as $transaction)
                                                <tr>
                                                    <td>
                                                        <div
                                                            class="form-check form-check-sm form-check-custom form-check-solid">
                                                            <input class="form-check-input" type="checkbox"
                                                                id="customer_checkbox_ids" name="customer_ids"
                                                                value="{{ $transaction['id'] }}" />
                                                        </div>
                                                    </td>
                                                    <td class="text-start">{{ $loop->iteration }}</td>
                                                    <td class="text-start">
                                                        {{ $transaction['subscription']['first_name'] ?? 'Deleted' }}
                                                        {{ $transaction['subscription']['last_name'] ?? 'User' }}
                                                    </td>
                                                    <td class="text-start">
                                                        {{ $transaction['subscription']['id'] ?? 'Deleted User' }}</td>
                                                    <td class="text-start">$
                                                        {{ $transaction['amount'] ?? 'Deleted User' }}
                                                    </td>
                                                    <td class="text-start"> {{ $transaction['status'] ?? 'Deleted User' }}
                                                    </td>
                                                    <td class="text-start">
                                                        <a class="view-btn m-0 pointer sub_admin_permission"
                                                            data-toggle="modal" data-target="#payment-details-modal"
                                                            data-id="{{ $transaction['id'] ?? 'Deleted User' }}"
                                                            data-name="{{ $transaction['subscription']['first_name'] ?? 'Deleted User' }}"
                                                            data-price="{{ $transaction['amount'] ?? 'Deleted User' }}"
                                                            data-subscription-id="{{ $transaction['subscription_id'] ?? 'Deleted User' }}"
                                                            data-customer-id="{{ $transaction['stripe_customer_id'] ?? 'Deleted User' }}"
                                                            data-subscription-status="{{ $transaction['status'] ?? 'Deleted User' }}"
                                                            data-start-date="{{ $transaction['current_period_start'] ?? 'Deleted User' }}"
                                                            data-end-date="{{ $transaction['current_period_end'] ?? 'Deleted User' }}"
                                                            data-next-date="{{ $transaction['next_payment_date'] ?? 'Deleted User' }}">View</a>
                                                    </td>
                                                </tr>
                                            @endforeach
                                        </tbody>

                                    </table>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Modal -->
                <div class="modal fade" id="payment-details-modal" tabindex="-1" role="dialog"
                    aria-labelledby="exampleModalLabel" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 550px;">
                        <div class="modal-content">
                            <div class="modal-body">
                                <div class="modal-header d-flex justify-content-between modal-title">
                                    <h5>View Details</h5>
                                    <button type="button pointer" class="btn-close" data-dismiss="modal"
                                        aria-label="Close">
                                        x
                                    </button>
                                </div>
                                <div class="row" style="padding: 0px 10px;">
                                    <div class="form-group subadmin-option col-md-12">
                                        <div class="payment-main-div">
                                            <div class="payment-inn-div">
                                                <p><strong>Name:</strong></p><span></span>
                                            </div>
                                            <div class="payment-inn-div">
                                                <p><strong>Price:</strong></p><span></span>
                                            </div>
                                            <div class="payment-inn-div">
                                                <p><strong>Subscription ID:</strong></p><span></span>
                                            </div>
                                            <div class="payment-inn-div">
                                                <p><strong>Stripe Customer Id:</strong></p><span></span>
                                            </div>
                                            <div class="payment-inn-div">
                                                <p><strong>Subscription Status:</strong></p><span></span>
                                            </div>
                                            <div class="payment-inn-div">
                                                <p><strong>Current Start Period:</strong></p><span></span>
                                            </div>
                                            <div class="payment-inn-div">
                                                <p><strong>Current End Period:</strong></p><span></span>
                                            </div>
                                            <div class="payment-inn-div">
                                                <p><strong>Next Period Date:</strong></p><span></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <div class="col-12 d-flex align-items-center p-0 mb-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body">
                        <h5>Referral Users</h5>
                        <form action="" method="POST" id="referral-users-form">
                            @csrf
                            <input type="hidden" name="selected_id" id="referral-ids" disabled>
                            <input type="hidden" name="all_id" id="all_referral_id" value="all" disabled>
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <table id="zero-config2" class="table dt-table-hover location_table" style="width:100%">
                                    <thead class="text-center">
                                        <tr>
                                            <th class="w-10px pe-2">
                                                <div
                                                    class="form-check form-check-sm form-check-custom form-check-solid me-3">
                                                    <input class="form-check-input" type="checkbox"
                                                        name="referral_user_ids" id="select-all-referral-ids" />
                                                </div>
                                            </th>
                                            <th class="text-start">Sr no</th>
                                            <th class="text-start">Name</th>
                                            <th class="text-start">Customer Id</th>
                                            <th class="text-start">Email</th>
                                            <th class="text-start">Count</th>
                                            <th class="text-start">Referred Users</th>
                                        </tr>
                                    </thead>
                                    <tbody class="text-center">
                                        @foreach ($referralData as $principalId => $data)
                                            <tr data-user="{{ json_encode($data['referred_user']) }}"
                                                data-referred-users="{{ json_encode($data['refeers_users']) }}">
                                                <td>
                                                    <div
                                                        class="form-check form-check-sm form-check-custom form-check-solid">
                                                        <input class="form-check-input" type="checkbox"
                                                            id="referral_user_checkbox_ids" name="referral_user_ids"
                                                            value="{{ $principalId }}" />
                                                    </div>
                                                </td>
                                                <td class="text-start">{{ $loop->iteration }}</td>
                                                <td class="text-start">{{ $data['referred_user']['first_name'] }}
                                                    {{ $data['referred_user']['last_name'] }}</td>
                                                <td class="text-start">{{ $data['referred_user']['id'] }}</td>
                                                <td class="text-start">{{ $data['referred_user']['email_address'] }}</td>
                                                <td class="text-start">
                                                    {{ count($data['refeers_users']) }}
                                                </td>
                                                <td class="text-start">
                                                    <a class="view-btn m-0 pointer btn-view-details" data-toggle="modal"
                                                        data-target="#referral-user-details-modal">
                                                        View
                                                    </a>
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>



                                </table>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal -->
        <div class="modal fade" id="referral-user-details-modal" tabindex="-1" role="dialog"
            aria-labelledby="referralUserDetailsModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered" role="document" style="max-width: 550px;">
                <div class="modal-content">
                    <div class="modal-body">
                        <div class="modal-header d-flex justify-content-between modal-title">
                            <h5>View Reffered User Details</h5>
                            <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close">
                                x
                            </button>
                        </div>
                        <div class="row" style="padding: 0px 10px;">
                            <div class="form-group subadmin-option col-md-12">
                                <div class="referral-user-main-div">
                                    <div class="referral-user-inn-div">
                                        <p><strong>Name:</strong></p><span></span>
                                    </div>
                                    <div class="referral-user-inn-div">
                                        <p><strong>Email:</strong></p><span></span>
                                    </div>
                                    {{-- <div class="referral-user-inn-div">
                                        <p><strong>Referral Code:</strong></p><span></span>
                                    </div> --}}
                                    <div class="referral-user-inn-div">
                                        <p><strong>Reffered Users:</strong></p><span></span>
                                    </div>
                                    <div class="referral-user-inn-div referred-users">
                                        <p><strong>Referred Users:</strong></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
    </div>
    </div>
@endsection

@section('section_script')
    <script src="{{ asset('public/assets/js/admin/dashboard/main.js') }}"></script>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            // Initial data and categories
            var userChartData = getUserChartData('monthly');
            var userCategories = getUserChartCategories('monthly');

            // Chart options
            var userOptions = {
                chart: {
                    type: 'line',
                    zoom: {
                        enabled: false
                    },
                    toolbar: {
                        show: false
                    }
                },
                series: userChartData,
                xaxis: {
                    categories: userCategories
                },
                stroke: {
                    curve: 'smooth',
                    width: [4, 4]
                }
            };

            // Create the chart
            var userChart = new ApexCharts(document.querySelector("#user-chart"), userOptions);
            userChart.render();

            // Event listener for filter select element
            document.getElementById('graph-filter').addEventListener('change', function(event) {
                var selectedFilter = event.target.value;
                userChartData = getUserChartData(selectedFilter);
                userCategories = getUserChartCategories(selectedFilter);

                userChart.updateSeries(userChartData);
                userChart.updateOptions({
                    xaxis: {
                        categories: userCategories
                    }
                });
            });

            // ------------ Sales chart starts ------------

            // Data for the sales chart
            var salesChartData = <?php echo json_encode(array_values($formattedDefaultData)); ?>;
            console.log("Initial Sales Chart Data:", salesChartData);

            // Chart options for the sales chart
            var salesOptions = {
                chart: {
                    type: 'bar',
                    zoom: {
                        enabled: false // Disable Zoom and Pan
                    },
                    toolbar: {
                        show: false // Hide the download button
                    }
                },
                series: [{
                    name: 'Sales',
                    data: salesChartData
                }],
                xaxis: {
                    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov',
                        'Dec'
                    ]
                },
                plotOptions: {
                    bar: {
                        columnWidth: '30%' // Adjust the bar width as needed
                    }
                },
                dataLabels: {
                    enabled: false // Hide the values on the bars
                }
            };

            // Create the chart with default data
            var salesChart = new ApexCharts(document.querySelector("#sales-chart"), salesOptions);
            salesChart.render();

            // Set default selected option to 'monthly' and trigger change event
            $('#sales-chart-options').val('monthly').trigger('change');

            // Event listener for select change
            $('#sales-chart-options').on('change', function() {
                console.log("Selected Option:", $(this).val()); // Log the selected option

                var selectedOption = $(this).val();
                var newData = [];
                var newXAxisCategories = [];

                // Fetch new data and adjust x-axis categories based on selected option
                switch (selectedOption) {
                    case 'monthly':
                        newData = <?php echo json_encode(array_values($formattedDefaultData)); ?>;
                        newXAxisCategories = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
                            'Oct', 'Nov', 'Dec'
                        ];
                        break;
                    case 'quarterly':
                        newData = <?php echo json_encode(array_values($quarterlyData)); ?>;
                        newXAxisCategories = ['Q1', 'Q2', 'Q3', 'Q4'];
                        break;
                    case 'yearly':
                        newData = <?php echo json_encode(array_values($yearlyData)); ?>;
                        newXAxisCategories = Object.keys(<?php echo json_encode($yearlyData); ?>);
                        break;
                    case 'daily':
                        newData = <?php echo json_encode(array_values($formattedDailyData)); ?>;
                        newXAxisCategories = Object.keys(<?php echo json_encode($formattedDailyData); ?>);
                        break;
                    default:
                        newData = <?php echo json_encode(array_values($formattedDefaultData)); ?>;
                        newXAxisCategories = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
                            'Oct', 'Nov', 'Dec'
                        ];
                        break;
                }

                console.log("New Data:", newData); // Log the new data
                console.log("New X-Axis Categories:", newXAxisCategories); // Log the new x-axis categories

                // Update chart data and x-axis categories with the new data
                salesChart.updateOptions({
                    series: [{
                        data: newData
                    }],
                    xaxis: {
                        categories: newXAxisCategories
                    }
                });
            });
        });

        function getUserChartData(filter) {
            switch (filter) {
                case 'monthly':
                    return [{
                        name: 'Total Accounts',
                        data: <?php echo json_encode(array_values($dataMonthlyWithType3)); ?>
                    }, {
                        name: 'Total Subscribed',
                        data: <?php echo json_encode(array_values($dataMonthlyWithType4)); ?>
                    }];
                case 'quarterly':
                    return [{
                        name: 'Total Accounts',
                        data: <?php echo json_encode(array_values($dataQuarterlyWithType3)); ?>
                    }, {
                        name: 'Total Subscribed',
                        data: <?php echo json_encode(array_values($dataQuarterlyWithType4)); ?>
                    }];
                case 'yearly':
                    return [{
                        name: 'Total Accounts',
                        data: <?php echo json_encode(array_values($dataYearlyWithType3)); ?>
                    }, {
                        name: 'Total Subscribed',
                        data: <?php echo json_encode(array_values($dataYearlyWithType4)); ?>
                    }];
                default:
                    return [];
            }
        }

        function getUserChartCategories(filter) {
            switch (filter) {
                case 'monthly':
                    return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                case 'quarterly':
                    return ['Q1', 'Q2', 'Q3', 'Q4'];
                case 'yearly':
                    return <?php echo json_encode(array_keys($dataYearlyWithType3)); ?>;
                default:
                    return [];
            }
        }
    </script>
@endsection
