<?php
// modules/sales/list_sales.php
session_start();
require_once '../assets/db_connect.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$shop_id = $_SESSION['user']['shop_id'] ?? 0;
$user_role = $_SESSION['user']['role'] ?? 'cashier';

if ($shop_id == 0) {
    die("Shop session missing.");
}

// Get default date range (last 30 days)
$default_from = date('Y-m-d', strtotime('-30 days'));
$default_to = date('Y-m-d');

// Get total stats for dashboard
$stats_sql = "SELECT 
                COUNT(DISTINCT s.id) as total_sales,
                SUM(s.total) as total_revenue,
                SUM(s.paid) as total_paid,
                AVG(s.total) as avg_sale,
                COUNT(DISTINCT s.customer_id) as total_customers
              FROM sales s
              WHERE s.shop_id = ?
              AND DATE(s.sale_date) BETWEEN ? AND ?";
$stats_stmt = $pdo->prepare($stats_sql);
$stats_stmt->execute([$shop_id, $default_from, $default_to]);
$stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
?>

<div class="col-md-10 ml-sm-auto px-4 py-4">
    <!-- Page Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h3 class="text-success mb-0">
                <i class="fas fa-chart-line"></i> Sales Management
            </h3>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb bg-transparent p-0">
                    <li class="breadcrumb-item"><a href="../dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Sales</li>
                </ol>
            </nav>
        </div>
        <div>
            <a href="pos.php" class="btn btn-primary">
                <i class="fas fa-cash-register"></i> New Sale
            </a>
            <button type="button" class="btn btn-success" onclick="printReport()">
                <i class="fas fa-print"></i> Print Report
            </button>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="row mb-4">
        <div class="col-md-2">
            <div class="card bg-info text-white">
                <div class="card-body text-center p-3">
                    <h6 class="card-title mb-1">Total Sales</h6>
                    <h3 class="mb-0"><?= number_format($stats['total_sales'] ?? 0) ?></h3>
                    <small>Transactions</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-success text-white">
                <div class="card-body text-center p-3">
                    <h6 class="card-title mb-1">Total Revenue</h6>
                    <h4 class="mb-0">TZS <?= number_format($stats['total_revenue'] ?? 0, 2) ?></h4>
                    <small>Gross Amount</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card bg-primary text-white">
                <div class="card-body text-center p-3">
                    <h6 class="card-title mb-1">Total Collected</h6>
                    <h4 class="mb-0">TZS <?= number_format($stats['total_paid'] ?? 0, 2) ?></h4>
                    <small>Amount Paid</small>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card bg-warning">
                <div class="card-body text-center p-3">
                    <h6 class="card-title mb-1">Avg. Sale</h6>
                    <h4 class="mb-0">TZS <?= number_format($stats['avg_sale'] ?? 0, 2) ?></h4>
                    <small>Per Transaction</small>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card bg-secondary text-white">
                <div class="card-body text-center p-3">
                    <h6 class="card-title mb-1">Customers</h6>
                    <h3 class="mb-0"><?= number_format($stats['total_customers'] ?? 0) ?></h3>
                    <small>Unique</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Filter Card -->
    <div class="card mb-4">
        <div class="card-header bg-light">
            <h5 class="mb-0"><i class="fas fa-filter"></i> Filter Sales</h5>
        </div>
        <div class="card-body">
            <form id="filterForm" class="row g-3">
                <div class="col-md-3">
                    <label class="form-label">From Date</label>
                    <input type="date" name="from_date" class="form-control" 
                           value="<?= $default_from ?>" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label">To Date</label>
                    <input type="date" name="to_date" class="form-control" 
                           value="<?= $default_to ?>" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-control">
                        <option value="">All Status</option>
                        <option value="paid">Paid</option>
                        <option value="open">Open</option>
                        <option value="partially_paid">Partially Paid</option>
                        <option value="cancelled">Cancelled</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Payment Method</label>
                    <select name="payment_method" class="form-control">
                        <option value="">All Methods</option>
                        <option value="CASH">Cash</option>
                        <option value="M-PESA">M-PESA</option>
                        <option value="TIGO-PESA">Tigo Pesa</option>
                        <option value="AIRTEL-MONEY">Airtel Money</option>
                        <option value="CARD">Card</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">&nbsp;</label>
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-search"></i> Filter
                        </button>
                    </div>
                </div>
            </form>
            
            <!-- Quick Date Filters -->
            <div class="row mt-3">
                <div class="col-md-12">
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('today')">
                            Today
                        </button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('yesterday')">
                            Yesterday
                        </button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('this_week')">
                            This Week
                        </button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('this_month')">
                            This Month
                        </button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="setDateRange('last_month')">
                            Last Month
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Sales Table -->
    <div class="card">
        <div class="card-header bg-light d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fas fa-list"></i> Sales List</h5>
            <div class="d-flex align-items-center">
                <div class="input-group input-group-sm mr-3" style="width: 200px;">
                    <input type="text" id="searchInput" class="form-control" placeholder="Search sales...">
                    <div class="input-group-append">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                    </div>
                </div>
                <div class="btn-group">
                    <button type="button" class="btn btn-sm btn-outline-success" onclick="exportToCSV()">
                        <i class="fas fa-file-csv"></i> Export
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-primary" onclick="printReport()">
                        <i class="fas fa-print"></i> Print
                    </button>
                </div>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-bordered table-hover mb-0" id="salesTable">
                    <thead class="thead-dark">
                        <tr>
                            <th width="50">ID</th>
                            <th width="120">Invoice No</th>
                            <th width="150">Date & Time</th>
                            <th>Customer</th>
                            <th width="80">Items</th>
                            <th width="100">Total</th>
                            <th width="100">Paid</th>
                            <th width="100">Due</th>
                            <th width="100">Payment</th>
                            <th width="90">Status</th>
                            <th width="100" class="no-print">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="salesBody">
                        <tr>
                            <td colspan="11" class="text-center py-4">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="sr-only">Loading...</span>
                                </div>
                                <p class="mt-2">Loading sales data...</p>
                            </td>
                        </tr>
                    </tbody>
                    <tfoot class="bg-light" id="salesFoot">
                        <tr>
                            <td colspan="5" class="text-right font-weight-bold">TOTALS:</td>
                            <td class="font-weight-bold text-success" id="totalSales">0.00</td>
                            <td class="font-weight-bold text-primary" id="totalPaid">0.00</td>
                            <td class="font-weight-bold text-danger" id="totalDue">0.00</td>
                            <td colspan="3"></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
        <div class="card-footer">
            <div class="row">
                <div class="col-md-6">
                    <div class="d-flex align-items-center">
                        <span class="mr-3">Show:</span>
                        <select id="rowsPerPage" class="form-control form-control-sm" style="width: 80px;">
                            <option value="10">10</option>
                            <option value="25" selected>25</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                        <span class="ml-3">rows per page</span>
                    </div>
                </div>
                <div class="col-md-6">
                    <nav aria-label="Page navigation" class="float-right">
                        <ul class="pagination pagination-sm mb-0" id="pagination">
                            <!-- Pagination will be added dynamically -->
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- View Sale Modal -->
<div class="modal fade" id="viewSaleModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Sale Details</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="saleDetails">
                <!-- Sale details will be loaded here -->
            </div>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>

<!-- Include necessary JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    // Load initial data
    loadSales();
    
    // Filter form submission
    $('#filterForm').on('submit', function(e) {
        e.preventDefault();
        loadSales();
    });
    
    // Rows per page change
    $('#rowsPerPage').change(function() {
        loadSales();
    });
    
    // Search functionality
    $('#searchInput').on('keyup', function() {
        const searchTerm = $(this).val().toLowerCase();
        if (searchTerm.length >= 2 || searchTerm.length === 0) {
            loadSales();
        }
    });
});

let currentPage = 1;
let totalPages = 1;

function loadSales(page = 1) {
    currentPage = page;
    
    const formData = new FormData(document.getElementById('filterForm'));
    formData.append('page', page);
    formData.append('rows_per_page', $('#rowsPerPage').val());
    formData.append('search', $('#searchInput').val());
    
    $('#salesBody').html(`
        <tr>
            <td colspan="11" class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="sr-only">Loading...</span>
                </div>
                <p class="mt-2">Loading sales data...</p>
            </td>
        </tr>
    `);
    
    $.ajax({
        url: 'load_sales.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                $('#salesBody').html(response.html);
                $('#totalSales').text(response.totals.total_sales.toFixed(2));
                $('#totalPaid').text(response.totals.total_paid.toFixed(2));
                $('#totalDue').text(response.totals.total_due.toFixed(2));
                
                totalPages = response.pagination.total_pages;
                updatePagination();
            } else {
                $('#salesBody').html(`
                    <tr>
                        <td colspan="11" class="text-center text-danger py-4">
                            <i class="fas fa-exclamation-circle fa-2x mb-2"></i>
                            <p>${response.message}</p>
                        </td>
                    </tr>
                `);
            }
        },
        error: function() {
            $('#salesBody').html(`
                <tr>
                    <td colspan="11" class="text-center text-danger py-4">
                        <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                        <p>Failed to load sales data. Please try again.</p>
                    </td>
                </tr>
            `);
        }
    });
}

function updatePagination() {
    const pagination = $('#pagination');
    pagination.empty();
    
    if (totalPages <= 1) return;
    
    // Previous button
    const prevDisabled = currentPage === 1 ? 'disabled' : '';
    pagination.append(`
        <li class="page-item ${prevDisabled}">
            <a class="page-link" href="#" onclick="loadSales(${currentPage - 1})" aria-label="Previous">
                <span aria-hidden="true">&laquo;</span>
            </a>
        </li>
    `);
    
    // Page numbers
    const maxVisible = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisible / 2));
    let endPage = Math.min(totalPages, startPage + maxVisible - 1);
    
    if (endPage - startPage + 1 < maxVisible) {
        startPage = Math.max(1, endPage - maxVisible + 1);
    }
    
    for (let i = startPage; i <= endPage; i++) {
        const active = i === currentPage ? 'active' : '';
        pagination.append(`
            <li class="page-item ${active}">
                <a class="page-link" href="#" onclick="loadSales(${i})">${i}</a>
            </li>
        `);
    }
    
    // Next button
    const nextDisabled = currentPage === totalPages ? 'disabled' : '';
    pagination.append(`
        <li class="page-item ${nextDisabled}">
            <a class="page-link" href="#" onclick="loadSales(${currentPage + 1})" aria-label="Next">
                <span aria-hidden="true">&raquo;</span>
            </a>
        </li>
    `);
}

function setDateRange(range) {
    const today = new Date();
    let fromDate, toDate;
    
    switch(range) {
        case 'today':
            fromDate = toDate = formatDate(today);
            break;
        case 'yesterday':
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            fromDate = toDate = formatDate(yesterday);
            break;
        case 'this_week':
            const firstDay = new Date(today.setDate(today.getDate() - today.getDay()));
            fromDate = formatDate(firstDay);
            toDate = formatDate(new Date());
            break;
        case 'this_month':
            fromDate = new Date(today.getFullYear(), today.getMonth(), 1);
            toDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
            fromDate = formatDate(fromDate);
            toDate = formatDate(toDate);
            break;
        case 'last_month':
            const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            fromDate = formatDate(lastMonth);
            toDate = formatDate(new Date(today.getFullYear(), today.getMonth(), 0));
            break;
    }
    
    $('input[name="from_date"]').val(fromDate);
    $('input[name="to_date"]').val(toDate);
    loadSales();
}

function formatDate(date) {
    return date.toISOString().split('T')[0];
}

function viewSale(saleId) {
    $.ajax({
        url: 'view_sale.php',
        type: 'GET',
        data: { id: saleId },
        success: function(response) {
            $('#saleDetails').html(response);
            $('#viewSaleModal').modal('show');
        }
    });
}

function printReceipt(saleId) {
    window.open(`print_receipt.php?id=${saleId}`, '_blank');
}

function deleteSale(saleId, invoiceNo) {
    Swal.fire({
        title: 'Delete Sale?',
        html: `Are you sure you want to delete sale <strong>${invoiceNo}</strong>?<br>
               <small class="text-muted">This will restore product stock and cannot be undone.</small>`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'delete_sale.php',
                type: 'POST',
                data: { id: saleId },
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        Swal.fire({
                            title: 'Deleted!',
                            text: response.message,
                            icon: 'success'
                        }).then(() => {
                            loadSales(currentPage);
                        });
                    } else {
                        Swal.fire({
                            title: 'Error!',
                            text: response.message,
                            icon: 'error'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        title: 'Error!',
                        text: 'Failed to delete sale. Please try again.',
                        icon: 'error'
                    });
                }
            });
        }
    });
}

function printReport() {
    const fromDate = $('input[name="from_date"]').val();
    const toDate = $('input[name="to_date"]').val();
    const status = $('select[name="status"]').val();
    const method = $('select[name="payment_method"]').val();
    
    const params = new URLSearchParams({
        from_date: fromDate,
        to_date: toDate,
        status: status,
        payment_method: method,
        print: '1'
    });
    
    window.open(`print_sales_report.php?${params.toString()}`, '_blank');
}

function exportToCSV() {
    const formData = new FormData(document.getElementById('filterForm'));
    
    $.ajax({
        url: 'export_sales.php',
        type: 'POST',
        data: formData,
        xhrFields: {
            responseType: 'blob'
        },
        success: function(blob) {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `sales_export_${new Date().toISOString().split('T')[0]}.csv`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        }
    });
}



//added
// In list_sales.php script section, update or add this function:
function printSalesReport() {
    const fromDate = $('input[name="from_date"]').val();
    const toDate = $('input[name="to_date"]').val();
    const status = $('select[name="status"]').val();
    const paymentMethod = $('select[name="payment_method"]').val();
    const search = $('#searchInput').val();
    
    // Build URL parameters
    let params = new URLSearchParams({
        from_date: fromDate,
        to_date: toDate,
        search: search
    });
    
    if (status) params.append('status', status);
    if (paymentMethod) params.append('payment_method', paymentMethod);
    
    // Open in new tab for printing
    const printUrl = `print_sales_report.php?${params.toString()}`;
    window.open(printUrl, '_blank', 'width=800,height=600');
}

</script>

<style>
.breadcrumb {
    background: transparent;
    padding: 0;
    margin-bottom: 1rem;
}
.breadcrumb-item a {
    color: #6c757d;
    text-decoration: none;
}
.breadcrumb-item.active {
    color: #28a745;
    font-weight: bold;
}
.card-header h5 {
    display: flex;
    align-items: center;
    gap: 10px;
}
.table th {
    font-weight: 600;
    white-space: nowrap;
}
.status-badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 600;
}
.status-paid { background: #28a745; color: white; }
.status-open { background: #ffc107; color: #212529; }
.status-partially_paid { background: #17a2b8; color: white; }
.status-cancelled { background: #dc3545; color: white; }
.payment-badge {
    padding: 3px 6px;
    border-radius: 3px;
    font-size: 11px;
    font-weight: 600;
    background: #6c757d;
    color: white;
}
.payment-CASH { background: #28a745; }
.payment-M-PESA { background: #007bff; }
.payment-TIGO-PESA { background: #6f42c1; }
.payment-AIRTEL-MONEY { background: #fd7e14; }
.payment-CARD { background: #17a2b8; }
.action-btn {
    padding: 4px 8px;
    font-size: 12px;
    margin: 0 2px;
}
</style>