<?php

session_start();
// Check if the user is logged in and if they have the correct role
if (!isset($_SESSION['username']) || ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'manager')) {
    header("Location: staff_sales.php");
    exit();
}

// Include database connection
include '../config/db.php';

// Update function name and query parameters
function getGroupedSalesData($pdo, $startDate = null, $endDate = null, $searchTerm = '') {
    $query = "SELECT * FROM sales WHERE 1=1";
    $params = [];

    if (!empty($searchTerm)) {
        $query .= " AND (username LIKE :search OR drug_name LIKE :search OR receipt LIKE :search)";
        $params['search'] = '%' . $searchTerm . '%';
    }

    // Add filter condition (date range)
    if ($startDate && $endDate) {
        $endDate = date('Y-m-d H:i:s', strtotime($endDate . ' 23:59:59'));
        $query .= " AND sale_date BETWEEN :start AND :end";
        $params['start'] = $startDate;
        $params['end'] = $endDate;
    }

    $query .= " ORDER BY sale_date DESC";
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $sales = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Group by receipt number
    $groupedSales = [];
    foreach ($sales as $sale) {
        $receipt = $sale['receipt'];
        if (!isset($groupedSales[$receipt])) {
            $groupedSales[$receipt] = [
                'receipt' => $receipt,
                'drug_id' => $sale['drug_id'], // Ensure drug_id is included
                'username' => $sale['username'],
                'total' => 0,
                'profit' => 0,
                'discount' => 0,
                'items' => [],
                'sale_date' => date('Y-m-d', strtotime($sale['sale_date'])) // Format the sale date
            ];
        }
        $groupedSales[$receipt]['items'][] = $sale;
        $groupedSales[$receipt]['total'] += $sale['total'];
        $groupedSales[$receipt]['profit'] += $sale['profit'];
        $groupedSales[$receipt]['discount'] += $sale['discount'];
    }

    return $groupedSales;
}


// Define date range based on filter
$filter = $_GET['filter'] ?? 'all';
$today = date('Y-m-d');
$startDate = $endDate = null;
$message = '';
$searchTerm = $_GET['search'] ?? '';

switch ($filter) {
    case 'daily':
        $startDate = $today;
        $endDate = $today;
        $message = "Showing sales for today: $today";
        break;
    case 'weekly':
        $startDate = date('Y-m-d', strtotime('last Sunday'));
        $endDate = $today;
        $message = "Showing sales from " . date('Y-m-d', strtotime('last Sunday')) . " to $today";
        break;
    case 'monthly':
        $startDate = date('Y-m-01');
        $endDate = $today;
        $message = "Showing sales from " . date('Y-m-01') . " to $today";
        break;
    case 'yearly':
        $startDate = date('Y-01-01');
        $endDate = $today;
        $message = "Showing sales from January 1, " . date('Y') . " to $today";
        break;
    case 'custom':
        $startDate = $_GET['start_date'] ?? $today;
        $endDate = $_GET['end_date'] ?? $today;
        $message = "Showing sales from $startDate to $endDate";
        break;
}

// Retrieve sales data based on the defined date range and search term
$salesData = getGroupedSalesData($pdo, $startDate, $endDate, $searchTerm);
$groupedSalesData = getGroupedSalesData($pdo, $startDate, $endDate, $searchTerm);

$totalSales = array_sum(array_column($salesData, 'total'));
$totalProfit = array_sum(array_column($salesData, 'profit'));
$totalDiscount = array_sum(array_column($salesData, 'discount'));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sales Report | Store Management</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <style>
        body {
            background-color: #f5f6fa;
            font-family: Arial, sans-serif;
            font-size: 14px;
        }

        .container {
            padding: 20px;
            scroll-padding-top: 70px; /* Height of your sticky header */
        }

        .top-bar {
            background-color: #ffffff;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }

        .summary-card {
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            transition: transform 0.3s ease;
        }

        .summary-card:hover {
            transform: translateY(-5px);
        }

        .sales-card { background: linear-gradient(135deg, #2980b9, #3498db); }
        .profit-card { background: linear-gradient(135deg, #27ae60, #2ecc71); }
        .discount-card { background: linear-gradient(135deg, #f39c12, #f1c40f); }

        .table-container {
            background: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            position: relative;
            z-index: 1;
        }

        .table thead th {
            background-color: #2c3e50;
            color: #fff;
            padding: 12px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #2c3e50, #3498db);
            border: none;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            background: #2980b9;
            transform: translateY(-2px);
        }

        .filter-btn {
            margin: 5px;
            transition: all 0.3s ease;
        }

        .filter-btn:hover {
            transform: translateY(-2px);
        }

        @media (max-width: 768px) {
            .summary-card { margin-bottom: 15px; }
            .filter-btn { width: 100%; margin-bottom: 5px; }
        }

        .badge {
            padding: 0.5em 0.75em;
            font-size: 0.875em;
        }

        .table-secondary {
            background-color: #f8f9fa;
        }

        .list-unstyled li {
            padding: 2px 0;
        }

        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.875rem;
            margin: 0 2px;
        }

        .badge.bg-warning {
            background-color: #ffc107 !important;
            color: #000 !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="top-bar">
            <div class="d-flex justify-content-between align-items-center">
                <h2><i class="fas fa-chart-line"></i> Sales Report</h2>
                <div>
                    <a href="admin_dashboard.php" class="btn btn-primary">
                        <i class="fas fa-arrow-left"></i> Dashboard
                    </a>
                    <a href="refunds.php" class="btn btn-warning">
                        <i class="fas fa-undo"></i> Refunds
                    </a>
                </div>
            </div>
        </div>

        <!-- Summary Cards -->
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="summary-card sales-card text-white">
                    <h5><i class="fas fa-shopping-cart"></i> Total Sales</h5>
                    <h3>₦<?= number_format($totalSales, 2) ?></h3>
                </div>
            </div>
            <div class="col-md-4">
                <div class="summary-card profit-card text-white">
                    <h5><i class="fas fa-chart-bar"></i> Total Profit</h5>
                    <h3>₦<?= number_format($totalProfit, 2) ?></h3>
                </div>
            </div>
            <div class="col-md-4">
                <div class="summary-card discount-card text-white">
                    <h5><i class="fas fa-tags"></i> Total Discount</h5>
                    <h3>₦<?= number_format($totalDiscount, 2) ?></h3>
                </div>
            </div>
        </div>

        <!-- Filter Options -->
        <div class="text-center mb-4">
            <a href="?filter=all&search=<?= htmlspecialchars($searchTerm) ?>" class="btn btn-outline-primary filter-btn">All</a>
            <a href="?filter=daily&search=<?= htmlspecialchars($searchTerm) ?>" class="btn btn-outline-primary filter-btn">Daily</a>
            <a href="?filter=weekly&search=<?= htmlspecialchars($searchTerm) ?>" class="btn btn-outline-primary filter-btn">Weekly</a>
            <a href="?filter=monthly&search=<?= htmlspecialchars($searchTerm) ?>" class="btn btn-outline-primary filter-btn">Monthly</a>
            <a href="?filter=yearly&search=<?= htmlspecialchars($searchTerm) ?>" class="btn btn-outline-primary filter-btn">Yearly</a>
            <button class="btn btn-outline-primary filter-btn" onclick="document.getElementById('customRange').style.display='block'">Custom Range</button>
        </div>

        <!-- Custom Range Filter -->
        <div id="customRange" style="display:none;" class="mb-4">
            <form method="get" action="">
                <input type="hidden" name="filter" value="custom">
                <div class="row">
                    <div class="col-md-5 col-sm-6">
                        <label for="start_date">Start Date</label>
                        <input type="date" name="start_date" id="start_date" class="form-control" required>
                    </div>
                    <div class="col-md-5 col-sm-6">
                        <label for="end_date">End Date</label>
                        <input type="date" name="end_date" id="end_date" class="form-control" required>
                    </div>
                    <div class="col-md-2 col-sm-12 mt-4">
                        <button type="submit" class="btn btn-primary">Apply</button>
                    </div>
                </div>
            </form>
        </div>

        <!-- Search Box -->
        <form method="get" action="" class="mb-3">
            <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
            <?php if ($filter == 'custom'): ?>
                <input type="hidden" name="start_date" value="<?= htmlspecialchars($startDate) ?>">
                <input type="hidden" name="end_date" value="<?= htmlspecialchars($endDate) ?>">
            <?php endif; ?>
            <div class="row">
                <div class="col-md-10">
                    <input type="text" name="search" class="form-control" placeholder="Search by username, drug name, or receipt ID" value="<?= htmlspecialchars($searchTerm) ?>">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary">Search</button>
                </div>
            </div>
        </form>

        <!-- Filter Message -->
        <?php if ($message): ?>
            <div class="alert alert-info text-center">
                <?= $message ?>
            </div>
        <?php endif; ?>

        <!-- Sales Table -->
        <table class="table table-bordered table-responsive-sm table-sm">
            <thead>
                <tr>
                    <th><i class="fas fa-calendar"></i> Date</th>
                    <th><i class="fas fa-user"></i> Staff</th>
                    <th><i class="fas fa-box"></i> Items</th>
                    <th><i class="fas fa-money-bill"></i> Total(₦)</th>
                    <th><i class="fas fa-chart-line"></i> Profit(₦)</th>
                    <th><i class="fas fa-tag"></i> Discount(₦)</th>
                    <th><i class="fas fa-cogs"></i> Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($groupedSalesData as $sale): ?>
                    <tr <?= ($sale['total'] <= 0) ? 'class="table-secondary"' : '' ?>>
                        <td><?= htmlspecialchars($sale['sale_date']) ?></td>
                        <td><?= htmlspecialchars($sale['username']) ?></td>
                        <td>
                            <ul class="list-unstyled mb-0">
                                <?php foreach ($sale['items'] as $item): ?>
                                    <li>
                                        <?= htmlspecialchars($item['drug_name']) ?> (<?= $item['quantity'] ?>)
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </td>
                        <td>
                            <?php if ($sale['total'] <= 0): ?>
                                <span class="badge bg-warning text-dark">
                                    <i class="fas fa-undo"></i> Refunded
                                </span>
                            <?php else: ?>
                                <?= number_format($sale['total'], 2) ?>
                            <?php endif; ?>
                        </td>
                        <td><?= number_format($sale['profit'], 2) ?></td>
                        <td><?= number_format($sale['discount'], 2) ?></td>
                        <td>
                            <a href="receipt.php?receipt_no=<?= $sale['receipt'] ?>" 
                               class="btn btn-sm btn-outline-primary">
                                <i class="fas fa-receipt"></i> View
                            </a>
                            <?php if ($sale['total'] > 0): ?>
                                <button type="button" 
                                        class="btn btn-sm btn-outline-danger" 
                                        data-toggle="modal" 
                                        data-target="#returnModal<?php echo $sale['receipt']; ?>">
                                    <i class="fas fa-undo"></i> Refund
                                </button>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php foreach ($groupedSalesData as $sale): ?>
    <!-- Modal for each receipt -->
    <div class="modal fade" id="returnModal<?php echo $sale['receipt']; ?>" tabindex="-1" role="dialog" aria-labelledby="returnModalLabel<?php echo $sale['receipt']; ?>" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-undo"></i> Refund for Receipt: <?php echo $sale['receipt']; ?>
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form method="POST" action="process_refund.php" onsubmit="return validateRefund(this);">
                    <div class="modal-body">
                        <input type="hidden" name="receipt" value="<?php echo $sale['receipt']; ?>">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i> Enter the quantity to refund for each item
                        </div>
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Sold Qty</th>
                                    <th>Refund Qty</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($sale['items'] as $item): ?>
                                    <tr>
                                        <td>
                                            <input type="hidden" name="drug_id[]" value="<?= $item['drug_id']; ?>">
                                            <?= htmlspecialchars($item['drug_name']); ?>
                                        </td>
                                        <td><?= $item['quantity']; ?></td>
                                        <td>
                                            <input type="number" name="refund_quantity[]" 
                                                   class="form-control form-control-sm"
                                                   min="0" max="<?= $item['quantity']; ?>">
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">
                            <i class="fas fa-times"></i> Cancel
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-check"></i> Process Refund
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<?php endforeach; ?>

<script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
<script src="..\libs\jquery\jquery-3.3.1.slim.min.js"></script>
<script src="../libs/bootsrtap/js/bootstrap.min.js"></script>
<script src="..\libs\popper\popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.2/dist/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
    $('#refundModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // Button that triggered the modal
        var receipt = button.data('receipt');
        var drug = button.data('drug');
        var quantity = button.data('quantity');
        
        // Populate the modal fields
        var modal = $(this);
        modal.find('#receipt').val(receipt);
        modal.find('#drug').val(drug);
        modal.find('#availableQuantity').val(quantity);
    });

    function validateRefund(form) {
        let hasRefund = false;
        const quantities = form.querySelectorAll('input[name="refund_quantity[]"]');
        
        for (let qty of quantities) {
            if (qty.value > 0) {
                hasRefund = true;
                if (qty.value > parseInt(qty.max)) {
                    alert('Refund quantity cannot be greater than sold quantity');
                    return false;
                }
            }
        }
        
        if (!hasRefund) {
            alert('Please enter at least one item to refund');
            return false;
        }
        
        return confirm('Are you sure you want to process this refund?');
    }
</script>
</body>
</html>
