@extends('admin.layout.dashboard_master')

@section('content')
    <main id="main" class="main">
        <div class="pagetitle">
            <h1>CSR Recycling Requests</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('american.plastic.admin.dashboard') }}">Home</a></li>
                    <li class="breadcrumb-item active">CSR Recycling</li>
                </ol>
            </nav>
        </div>

        <section class="section">
            <!-- Point Summary Cards -->
            <style>
                .premium-card {
                    border: none;
                    border-radius: 15px;
                    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
                    transition: all 0.3s ease;
                    overflow: hidden;
                    background: #fff;
                }

                .premium-card:hover {
                    transform: translateY(-5px);
                    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.1);
                }

                .icon-box {
                    width: 48px;
                    height: 48px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border-radius: 12px;
                    font-size: 24px;
                }

                .bg-success-light {
                    background-color: rgba(46, 202, 106, 0.1);
                    color: #2eca6a;
                }

                .bg-warning-light {
                    background-color: rgba(255, 119, 29, 0.1);
                    color: #ff771d;
                }
            </style>
            <div class="row mb-4">
                <div class="col-md-6 col-lg-3">
                    <div class="card premium-card p-3">
                        <div class="d-flex align-items-center">
                            <div class="icon-box bg-success-light me-3">
                                <i class="bi bi-gift-fill"></i>
                            </div>
                            <div>
                                <p class="text-muted small mb-0">Total Points Allocated</p>
                                <h4 class="mb-0 fw-bold">{{ number_format($collectedPoints, 2) }}</h4>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-6 col-lg-3">
                    <div class="card premium-card p-3">
                        <div class="d-flex align-items-center">
                            <div class="icon-box bg-warning-light me-3">
                                <i class="bi bi-hourglass-split"></i>
                            </div>
                            <div>
                                <p class="text-muted small mb-0">Total Points Allocating</p>
                                <h4 class="mb-0 fw-bold">{{ number_format($collectingPoints, 2) }}</h4>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body pt-4">
                            <div class="row mb-4 align-items-end">
                                <div class="col-md-3">
                                    <label for="status-filter" class="form-label fw-bold">Filter by Status</label>
                                    <select id="status-filter" class="form-select">
                                        <option value="">All Statuses</option>
                                        <option value="pending">Pending</option>
                                        <option value="collecting">Collecting</option>
                                        <option value="completed">Completed</option>
                                        <option value="rejected">Rejected</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="product-source-filter" class="form-label fw-bold">Filter by Product Type</label>
                                    <select id="product-source-filter" class="form-select">
                                        <option value="">All Products</option>
                                        <option value="catalog">Choose from Catalog</option>
                                        <option value="typed">Typed/Custom Product</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <button type="button" id="export-btn" class="btn btn-success w-100" style="height: 38px;">
                                        <i class="fas fa-file-excel me-1"></i> Export Excel
                                    </button>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table table-hover" id="recycling-table" style="width:100%">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Date</th>
                                            <th>User</th>
                                            <th>Product</th>
                                            <th>Qty</th>
                                            <th>Weight</th>
                                            <th>Points</th>
                                            <th>Image</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- Status Modal -->
    <div class="modal fade" id="statusModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Process Recycling Request</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="statusForm">
                    @csrf
                    <input type="hidden" name="id" id="request_id">
                    <input type="hidden" name="status" id="request_status">
                    <div class="modal-body">
                        <p id="status-text"></p>

                        <div id="weight-container" class="mb-3 d-none">
                            <div class="row">
                                <div class="col-md-8">
                                    <label for="weight" class="form-label fw-bold">Weight <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" name="weight" id="weight" min="0" step="0.01">
                                </div>
                                <div class="col-md-4">
                                    <label for="uom" class="form-label fw-bold">UOM</label>
                                    <input type="text" class="form-control" name="uom" id="uom" value="g" readonly>
                                </div>
                            </div>
                        </div>

                        <div id="points-container" class="mb-3 d-none">
                            <label for="total_points" class="form-label fw-bold">Points to be credited <span
                                    class="text-danger">*</span></label>
                            <input type="number" class="form-control" name="total_points" id="total_points" min="0"
                                step="0.01" readonly>
                            <small class="text-muted">Calculated: Catalog product 1g = 0.15 pts, Custom product 1g = 0.10 pts.</small>
                        </div>

                        <div class="mb-3">
                            <label for="admin_note" class="form-label fw-bold">Note <span
                                    class="text-danger">*</span></label>
                            <textarea class="form-control" name="admin_note" id="admin_note" rows="3" required
                                placeholder="Reason for approval/rejection..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn" id="submit-btn"></button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Export Modal -->
    <div class="modal fade" id="exportModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Export CSR Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="export-status" class="form-label fw-bold">Select Status for Export <span
                                class="text-danger">*</span></label>
                        <select id="export-status" class="form-select">
                            <option value="">All Statuses</option>
                            <option value="pending">Pending</option>
                            <option value="collecting">Collecting</option>
                            <option value="completed">Completed</option>
                            <option value="rejected">Rejected</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="export-product-source" class="form-label fw-bold">Select Product Type for Export <span
                                class="text-danger">*</span></label>
                        <select id="export-product-source" class="form-select">
                            <option value="">All Products</option>
                            <option value="catalog">Choose from Catalog</option>
                            <option value="typed">Typed/Custom Product</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" id="confirm-export-btn" class="btn btn-success">
                        <i class="fas fa-file-excel me-1"></i> Download Report
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function () {
            var table = $('#recycling-table').DataTable({
                processing: true,
                serverSide: true,
                order: [[1, 'desc']],
                ajax: {
                    url: "{{ route('admin.csr.data') }}",
                    data: function (d) {
                        d.status = $('#status-filter').val();
                        d.product_source = $('#product-source-filter').val();
                    }
                },
                columns: [
                    { data: 'DT_RowIndex', name: 'DT_RowIndex' },
                    {
                        data: 'created_at', name: 'created_at', render: function (data) {
                            return new Date(data).toLocaleDateString();
                        }
                    },
                    { data: 'user_name', name: 'user_name' },
                    { data: 'product_info', name: 'product_info' },
                    { data: 'quantity', name: 'quantity' },
                    { data: 'weight_info', name: 'weight_info' },
                    { data: 'total_points', name: 'total_points' },
                    { data: 'image', name: 'image', orderable: false, searchable: false },
                    { data: 'status_label', name: 'status_label' },
                    { data: 'action', name: 'action', orderable: false, searchable: false }
                ]
            });

            $('#status-filter').on('change', function () {
                table.ajax.reload();
            });

            $('#product-source-filter').on('change', function () {
                table.ajax.reload();
            });

            $('#export-btn').on('click', function () {
                $('#export-status').val($('#status-filter').val());
                $('#export-product-source').val($('#product-source-filter').val());
                $('#exportModal').modal('show');
            });

            $('#confirm-export-btn').on('click', function () {
                var status = $('#export-status').val();
                var productSource = $('#export-product-source').val();
                var url = "{{ route('admin.csr.export') }}";
                var params = [];
                if (status) {
                    params.push("status=" + status);
                }
                if (productSource) {
                    params.push("product_source=" + productSource);
                }
                if (params.length > 0) {
                    url += "?" + params.join("&");
                }
                $('#exportModal').modal('hide');
                window.location.href = url;
            });

            window.updateStatus = function (id, status, points, weight, uom, isCatalog) {
                $('#request_id').val(id);
                $('#request_status').val(status);
                $('#status-text').text('Are you sure you want to change the status of this request to "' + status + '"?');
                $('#admin_note').val('');

                // Reset fields
                $('#points-container').addClass('d-none');
                $('#weight-container').addClass('d-none');
                
                // Save info in modal data attributes
                $('#statusModal').data('is-catalog', isCatalog);

                $('#weight').val(weight || '');
                $('#uom').val(uom || 'g');

                // Trigger dynamic points calculation immediately based on weight
                $('#weight').trigger('input');

                const btn = $('#submit-btn');
                if (status === 'completed' || status === 'approved') {
                    btn.text('Approve & Complete').removeClass('btn-danger btn-info').addClass('btn-success');
                    $('#weight-container').removeClass('d-none');
                    $('#points-container').removeClass('d-none');
                    $('#weight').prop('required', true);
                    $('#admin_note').prop('required', true);
                } else if (status === 'collecting') {
                    btn.text('Start Collecting').removeClass('btn-danger btn-success').addClass('btn-info text-white');
                    $('#weight-container').removeClass('d-none');
                    $('#weight').prop('required', true);
                    $('#admin_note').prop('required', false);
                } else {
                    btn.text('Reject').removeClass('btn-success btn-info').addClass('btn-danger');
                    $('#admin_note').prop('required', true);
                    $('#weight').prop('required', false);
                }

                $('#statusModal').modal('show');
            };

            // Calculate points dynamically on weight input
            $('#weight').on('input change', function () {
                const weight = parseFloat($(this).val()) || 0;
                const isCatalog = $('#statusModal').data('is-catalog');
                const rate = isCatalog ? 0.15 : 0.10;
                const points = weight * rate;
                $('#total_points').val(points.toFixed(2));
            });

            $('#statusForm').on('submit', function (e) {
                e.preventDefault();

                const btn = $('#submit-btn');
                btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Processing...');

                $.ajax({
                    url: "{{ route('admin.csr.update') }}",
                    type: "POST",
                    data: $(this).serialize(),
                    success: function (response) {
                        if (response.success) {
                            $('#statusModal').modal('hide');
                            Alert.success(response.message);
                            setTimeout(function () {
                                window.location.reload();
                            }, 1000);
                        } else {
                            Alert.error(response.message);
                        }
                    },
                    error: function (xhr) {
                        Alert.error(xhr.responseJSON.message || 'Error processing request');
                    },
                    complete: function () {
                        btn.prop('disabled', false).text(btn.text());
                    }
                });
            });
        });
    </script>
@endsection