<?php
session_start();

// Check if the user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

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

// Get the logged-in username
$username = $_SESSION['username'];

function getGroupedSalesData($pdo, $startDate = null, $endDate = null, $searchTerm = '') {
    global $username; // Use the logged-in user's username

    $query = "SELECT * FROM sales WHERE username = :username";  // Filter by username
    $params = ['username' => $username]; // Bind the logged-in username

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

    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,
                '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"> <!-- Ensures mobile responsiveness -->
    <title>Sales Report</title>
    <link rel="stylesheet" href="..\libs\bootsrtap\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <script src="..\libs\popper\popper.min.js"></script>
    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\jquery\jquery-3.3.1.slim.min.js"></script>


    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        body { background-color: #f8f9fa; }
        .filter-btn { margin-right: 5px; }
        .table th, .table td { text-align: center; padding: 5px; } /* Reduces cell padding */
        .table-sm td, .table-sm th { font-size: 0.85rem; padding: 0.3rem; } /* Smaller font and padding for compact look */
        .btn-print { color: white; background-color: #007bff; }
        .btn-back { background-color: #6c757d; color: white; }
        @media (max-width: 768px) {
            .table-sm th, .table-sm td { font-size: 0.75rem; } /* Adjusts text size for smaller devices */
            .filter-btn { font-size: 0.9rem; margin-bottom: 5px; } /* Makes filter buttons more compact */
            .card-body { padding: 0.5rem; } /* Reduces padding in card body */
        }
    </style>
</head>
<body>
<div class="container mt-4">
    <h3 class="text-center mb-4">Sales Report For <?php echo $username;?></h3>

    <!-- Back to Admin Dashboard Button -->
    <div class="text-center mb-3">
        <a href="admin_dashboard.php" class="btn btn-back">Back to Dashboard</a>
    </div>
    <?php if (isset($_SESSION['success'])): ?>
    <div class="alert alert-success">
        <?= $_SESSION['success']; unset($_SESSION['success']); ?>
    </div>
<?php endif; ?>
<?php if (isset($_SESSION['error'])): ?>
    <div class="alert alert-danger">
        <?= $_SESSION['error']; unset($_SESSION['error']); ?>
    </div>
<?php endif; ?>


    <!-- Filter Options -->
    <div class="text-center mb-3">
        <a href="?filter=all" class="btn btn-outline-primary filter-btn">All</a>
        <a href="?filter=daily" class="btn btn-outline-primary filter-btn">Daily</a>
        <a href="?filter=weekly" class="btn btn-outline-primary filter-btn">Weekly</a>
        <a href="?filter=monthly" class="btn btn-outline-primary filter-btn">Monthly</a>
        <a href="?filter=yearly" 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">
        <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; ?>

    <!-- Summary Cards -->
    <div class="row text-center mb-4">
        <div class="col-md-4 mb-3">
            <div class="p-3 bg-primary text-white rounded">
                <h5>Total Sales (₦)</h5>
                <h3><?= number_format($totalSales, 2) ?></h3>
            </div>
        </div>
       
        <div class="col-md-4 mb-3">
            <div class="p-3 bg-warning text-white rounded">
                <h5>Total Discount (₦)</h5>
                <h3><?= number_format($totalDiscount, 2) ?></h3>
            </div>
        </div>
    </div>

    <!-- Sales Table -->
    <table class="table table-bordered table-responsive-sm table-sm">
        <thead>
            <tr>
                <th>Date </th>
                <th>Username</th>
                <th>Items</th>
                <th>Total(₦)</th>
              
                <th>Discount (₦)</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($groupedSalesData as $sale): ?>
                <tr>
                <td><?= htmlspecialchars($sale['sale_date']) ?></td>
                    <td><?= htmlspecialchars($sale['username']) ?></td>
                    <td>
                        <ul>
                            <?php foreach ($sale['items'] as $item): ?>
                                <li><?= htmlspecialchars($item['drug_name']) ?> (<?= $item['quantity'] ?>)</li>
                            <?php endforeach; ?>
                        </ul>
                    </td>
                    <td><?= number_format($sale['total'], 2) ?></td>
                 
                    <td><?= number_format($sale['discount'], 2) ?></td>
                    <td>
    <a href="receipt.php?receipt_no=<?= $sale['receipt'] ?>" class="btn btn-print btn-sm">View Receipt</a>
    <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#returnModal<?php echo $sale['receipt']; ?>">
                    Refund
                </button>
</td>

                           
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</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" id="returnModalLabel<?php echo $sale['receipt']; ?>">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">
    <div class="modal-body">
        <input type="hidden" name="receipt" value="<?php echo $sale['receipt']; ?>">
        <table class="table">
            <thead>
                <tr>
                    <th>Drug Name</th>
                    <th>Quantity</th>
                    <th>Refund Quantity</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($sale['items'] as $item): ?>
                    <tr>
                        <td>
                            <input type="hidden" name="drug_id[]" value="<?= $item['id']; ?>">
                            <input type="hidden" name="drug_name[]" value="<?= $item['drug_name']; ?>">
                            <?= htmlspecialchars($item['drug_name']); ?>
                        </td>
                        <td><?= $item['quantity']; ?></td>
                        <td>
                            <input type="number" name="refund_quantity[]" min="1" max="<?= $item['quantity']; ?>" class="form-control">
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <div class="modal-footer">
        <button type="submit" class="btn btn-primary">Process Refund</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    </div>
</form>

            </div>
        </div>
    </div>
<?php endforeach; ?>


<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);
    });
</script>

</body>
</html>
