<?php
session_start();
if (!isset($_SESSION['username'])) {
    exit("Unauthorized");
}
require_once "db.php";

$from_date = isset($_GET['from_date']) ? $_GET['from_date'] : date("Y-m-01");
$to_date   = isset($_GET['to_date']) ? $_GET['to_date'] : date("Y-m-d");

// Detect if user searched by exact dates
$is_date_to_date = (strlen($from_date) == 10 && strlen($to_date) == 10);

// Function to get report rows (same as report page)
function get_report($conn, $from_date, $to_date, $is_date_to_date) {
    if ($is_date_to_date) {
        $sql = "SELECT DATE(s.sale_date) as period,
                       SUM(s.total) as sales,
                       (SELECT IFNULL(SUM(p.total),0) FROM purchases p WHERE DATE(p.purchase_date)=DATE(s.sale_date)) as cogs,
                       (SELECT IFNULL(SUM(e.amount),0) FROM expenses e WHERE DATE(e.created_at)=DATE(s.sale_date)) as expenses
                FROM sales s
                WHERE DATE(s.sale_date) BETWEEN ? AND ?
                GROUP BY period ORDER BY period ASC";
    } else {
        $sql = "SELECT DATE_FORMAT(s.sale_date,'%Y-%m') as period,
                       SUM(s.total) as sales,
                       (SELECT IFNULL(SUM(p.total),0) FROM purchases p WHERE DATE_FORMAT(p.purchase_date,'%Y-%m')=DATE_FORMAT(s.sale_date,'%Y-%m')) as cogs,
                       (SELECT IFNULL(SUM(e.amount),0) FROM expenses e WHERE DATE_FORMAT(e.created_at,'%Y-%m')=DATE_FORMAT(s.sale_date,'%Y-%m')) as expenses
                FROM sales s
                WHERE DATE_FORMAT(s.sale_date,'%Y-%m') BETWEEN ? AND ?
                GROUP BY period ORDER BY period ASC";
    }
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $from_date, $to_date);
    $stmt->execute();
    $res = $stmt->get_result();

    $rows = [];
    while ($r = $res->fetch_assoc()) {
        $r['gross_profit'] = $r['sales'] - $r['cogs'];
        $r['net_profit']   = $r['gross_profit'] - $r['expenses'];
        $rows[] = $r;
    }
    return $rows;
}

$data = get_report($conn, $from_date, $to_date, $is_date_to_date);

// Totals
$total_sales = $total_cogs = $total_gross = $total_exp = $total_net = 0;
foreach ($data as $row) {
    $total_sales += $row['sales'];
    $total_cogs  += $row['cogs'];
    $total_gross += $row['gross_profit'];
    $total_exp   += $row['expenses'];
    $total_net   += $row['net_profit'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Profit & Loss Report Print</title>
  <style>
    body { font-family: Arial, sans-serif; margin:20px; }
    h2 { text-align:center; }
    table { width:100%; border-collapse:collapse; margin-top:20px; }
    th, td { border:1px solid #333; padding:8px; text-align:center; }
    th { background:#f2f2f2; }
    tfoot td { font-weight:bold; background:#fafafa; }
    .footer { margin-top:50px; display:flex; justify-content:space-between; }
  </style>
</head>
<body onload="window.print()" class="global-print">

  <?php
    include("global/global-print-heading.php");
?>
  <h3 style="text-align:center;">Profit & Loss Report</h3>
  <p style="text-align:center;">From <?php echo $from_date; ?> To <?php echo $to_date; ?></p>

  <table>
    <thead>
      <tr>
        <th><?php echo $is_date_to_date ? "Date" : "Month"; ?></th>
        <th>Sales</th>
        <th>COGS</th>
        <th>Gross Profit</th>
        <th>Expenses</th>
        <th>Net Profit</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($data as $row): ?>
        <tr>
          <td><?php echo $is_date_to_date ? date("d M Y", strtotime($row['period'])) : date("M Y", strtotime($row['period']."-01")); ?></td>
          <td><?php echo number_format($row['sales'],2); ?></td>
          <td><?php echo number_format($row['cogs'],2); ?></td>
          <td><?php echo number_format($row['gross_profit'],2); ?></td>
          <td><?php echo number_format($row['expenses'],2); ?></td>
          <td><?php echo number_format($row['net_profit'],2); ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
    <tfoot>
      <tr>
        <td>Total</td>
        <td><?php echo number_format($total_sales,2); ?></td>
        <td><?php echo number_format($total_cogs,2); ?></td>
        <td><?php echo number_format($total_gross,2); ?></td>
        <td><?php echo number_format($total_exp,2); ?></td>
        <td><?php echo number_format($total_net,2); ?></td>
      </tr>
    </tfoot>
  </table>
 <?php
    include("global/global-print-footer.php");
?>
  
</body>
</html>
