<?php session_start();
include('../includes/header.php'); 
include('../includes/sidebar.php'); 
require '../../config/db_connect.php';


// Allow only admins
if (!isset($_SESSION['user']) || $_SESSION['user']['role'] != 'admin') {
    die("Access denied. Admin only.");
}

// Get date range from form or set default
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// Fetch profit per product within date range
$sql = "
    SELECT 
        p.id,
        p.name,
        SUM(sl.qty) AS total_sold,
        SUM(sl.line_total) AS revenue,
        SUM(sl.qty * pb.cost_price) AS total_cost,
        (SUM(sl.line_total) - SUM(sl.qty * pb.cost_price)) AS profit
    FROM sale_lines sl
    JOIN product_batches pb ON pb.id = sl.batch_id
    JOIN products p ON p.id = sl.product_id
    JOIN sales s ON s.id = sl.sale_id
    WHERE s.status != 'cancelled' 
      AND DATE(s.sale_date) BETWEEN :start_date AND :end_date
    GROUP BY p.id
    ORDER BY profit DESC
";
$stmt = $pdo->prepare($sql);
$stmt->execute(['start_date' => $start_date, 'end_date' => $end_date]);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
/* Back button styling - consistent with other pages */
.back-btn {
    display: inline-block;
    padding: 8px 16px;
    background-color: #6c757d;
    color: white;
    text-decoration: none;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    font-size: 14px;
    margin-bottom: 15px;
    transition: background-color 0.2s;
}
.back-btn:hover {
    background-color: #5a6268;
    color: white;
    text-decoration: none;
}
.back-btn i {
    margin-right: 5px;
}
/* Print-only styling */
@media print {
    .no-print, .back-btn {
        display: none !important;
    }
}
</style>

<div class="col-md-10 ml-sm-auto px-4 py-4">

<!-- BACK BUTTON at the top -->
<div class="mb-3 no-print">
    <a href="daily_sales.php" class="back-btn">
        <i>←</i> Back to Reports
    </a>
</div>

    <div class="card mt-3">
        <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Profit Report (Products)</h5>
            <form class="form-inline no-print" method="get">
                <input type="date" name="start_date" class="form-control form-control-sm mr-2" value="<?= htmlspecialchars($start_date) ?>" required>
                <input type="date" name="end_date" class="form-control form-control-sm mr-2" value="<?= htmlspecialchars($end_date) ?>" required>
                <button type="submit" class="btn btn-sm btn-light mr-2">Filter</button>
                <button type="button" class="btn btn-sm btn-warning" onclick="printReport()">Print</button>
            </form>
        </div>
        <div class="card-body" id="printArea">
            <p><strong>Date Range:</strong> <?= date('d-M-Y', strtotime($start_date)) ?> to <?= date('d-M-Y', strtotime($end_date)) ?></p>
            
            <?php 
            $total_sold = 0;
            $total_revenue = 0;
            $total_cost = 0;
            $total_profit = 0;
            
            foreach ($data as $row) {
                $total_sold += $row['total_sold'];
                $total_revenue += $row['revenue'];
                $total_cost += $row['total_cost'];
                $total_profit += $row['profit'];
            }
            ?>
            
            <div class="row mb-3 no-print">
                <div class="col-md-3">
                    <div class="card text-white bg-primary">
                        <div class="card-body p-2">
                            <h6 class="card-title mb-1">Total Sold</h6>
                            <p class="card-text h4 mb-0"><?= number_format($total_sold) ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-white bg-info">
                        <div class="card-body p-2">
                            <h6 class="card-title mb-1">Total Revenue</h6>
                            <p class="card-text h4 mb-0"><?= number_format($total_revenue, 2) ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-white bg-secondary">
                        <div class="card-body p-2">
                            <h6 class="card-title mb-1">Total Cost</h6>
                            <p class="card-text h4 mb-0"><?= number_format($total_cost, 2) ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-white <?= $total_profit >= 0 ? 'bg-success' : 'bg-danger' ?>">
                        <div class="card-body p-2">
                            <h6 class="card-title mb-1">Total Profit</h6>
                            <p class="card-text h4 mb-0"><?= number_format($total_profit, 2) ?></p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="table-responsive">
                <table class="table table-bordered table-hover table-sm">
                    <thead class="thead-dark">
                        <tr>
                            <th>#</th>
                            <th>Product</th>
                            <th>Total Sold</th>
                            <th>Revenue</th>
                            <th>Cost</th>
                            <th>Profit</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$data): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted">No sales available for this date range.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($data as $i => $row): ?>
                                <tr>
                                    <td><?= $i+1 ?></td>
                                    <td><?= htmlspecialchars($row['name']) ?></td>
                                    <td><?= $row['total_sold'] ?></td>
                                    <td><?= number_format($row['revenue'],2) ?></td>
                                    <td><?= number_format($row['total_cost'],2) ?></td>
                                    <td class="<?= ($row['profit'] < 0 ? 'text-danger' : 'text-success') ?>">
                                        <b><?= number_format($row['profit'],2) ?></b>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                    <tfoot class="table-secondary">
                        <tr>
                            <td colspan="2" class="text-right"><strong>Totals:</strong></td>
                            <td><strong><?= number_format($total_sold) ?></strong></td>
                            <td><strong><?= number_format($total_revenue, 2) ?></strong></td>
                            <td><strong><?= number_format($total_cost, 2) ?></strong></td>
                            <td class="<?= $total_profit >= 0 ? 'text-success' : 'text-danger' ?>">
                                <strong><?= number_format($total_profit, 2) ?></strong>
                            </td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
    
    <!-- BACK BUTTON at the bottom -->
    <div class="mt-4 no-print">
        <a href="daily_sales.php" class="back-btn">
            <i>←</i> Back to Reports
        </a>
    </div>

</div>

<script>
function printReport() {
    const printContents = document.getElementById('printArea').innerHTML;
    const originalContents = document.body.innerHTML;

    document.body.innerHTML = `
        <html>
        <head>
            <title>Print Profit Report</title>
            <link rel="stylesheet" href="../../libraries/bootstrap.css">
            <style>
                table { width: 100%; border-collapse: collapse; }
                th, td { border: 1px solid #000 !important; padding: 5px; }
                th { background-color: #343a40; color: #fff; }
                .text-danger { color: red; }
                .text-success { color: green; }
                @media print {
                    body { padding: 20px; }
                }
            </style>
        </head>
        <body>
            <h3 class="text-center mb-3">Profit Report (Products)</h3>
            <div class="text-center mb-3">
                <strong>Date Range:</strong> <?= date('d-M-Y', strtotime($start_date)) ?> to <?= date('d-M-Y', strtotime($end_date)) ?>
            </div>
            ${printContents}
            <div class="text-center mt-4">
                <button onclick="window.print()" class="btn btn-primary mr-2">Print</button>
                <button onclick="window.close()" class="btn btn-secondary">Close</button>
            </div>
        </body>
        </html>
    `;

    window.focus();
}
</script>

<?php include('../includes/footer.php'); ?>