<?php
require_once '../includes/auth.php';
requirePermission('reports', 'export');
require_once '../db.php';
require_once '../vendor/autoload.php';

use Dompdf\Dompdf;

$from   = $_GET['from'] ?? "";
$to     = $_GET['to'] ?? "";
$search = $_GET['search'] ?? "";
$batch  = (int)($_GET['batch'] ?? 0);

$where = " WHERE p.company_id = $cid ";

if (!empty($from) && !empty($to)) {
    $where .= " AND DATE(sm.created_at) BETWEEN '$from' AND '$to' ";
}

if (!empty($search)) {
    $s = $conn->real_escape_string($search);
    $where .= " AND (p.name LIKE '%$s%' OR sm.type LIKE '%$s%' OR pi.batch_no LIKE '%$s%') ";
}

$html = "
<style>
    body { font-family: DejaVu Sans, Arial; font-size: 12px; }
    h2 { text-align:center; margin-bottom:5px; }
    .meta { text-align:center; font-size:11px; margin-bottom:10px; }
    table { width:100%; border-collapse: collapse; }
    th, td { border:1px solid #000; padding:6px; font-size:11px; }
    th { background:#f2f2f2; }
</style>
";

$html .= "<h2>Stock Movement Report</h2>";
$html .= "<div class='meta'>From: <b>$from</b> &nbsp;&nbsp; To: <b>$to</b></div>";

/* ================================
   BATCH WISE PDF
================================ */
if ($batch === 1) {

    $sql = "
    SELECT 
        sm.created_at,
        p.name AS product_name,
        pi.batch_no,
        sm.type,
        sm.quantity,
        sm.reference_type,
        sm.reference_id
    FROM stock_movements sm
    JOIN products p ON p.id = sm.product_id
    LEFT JOIN purchase_items pi ON pi.id = sm.purchase_item_id
    $where
    ORDER BY sm.created_at DESC
    ";

    $res = $conn->query($sql);

    $html .= "<table>
        <tr>
            <th>Date</th>
            <th>Product</th>
            <th>Batch</th>
            <th>Type</th>
            <th>Qty</th>
            <th>Reference</th>
        </tr>";

    while ($row = $res->fetch_assoc()) {

        $ref = "-";
        if (!empty($row['reference_type']) && !empty($row['reference_id'])) {
            $ref = strtoupper($row['reference_type']) . " #" . $row['reference_id'];
        }

        $html .= "<tr>
            <td>" . date("d-m-Y h:i A", strtotime($row['created_at'])) . "</td>
            <td>" . htmlspecialchars($row['product_name']) . "</td>
            <td>" . htmlspecialchars($row['batch_no'] ?? '-') . "</td>
            <td>" . htmlspecialchars($row['type']) . "</td>
            <td>" . htmlspecialchars($row['quantity']) . "</td>
            <td>" . htmlspecialchars($ref) . "</td>
        </tr>";
    }

    $html .= "</table>";

} else {

    /* ================================
       PRODUCT SUMMARY PDF
    ================================ */

    $sql = "
    SELECT 
        sm.product_id,
        p.name AS product_name,
        SUM(CASE WHEN sm.type='IN' THEN sm.quantity ELSE 0 END) AS total_in,
        SUM(CASE WHEN sm.type='OUT' THEN sm.quantity ELSE 0 END) AS total_out,
        SUM(CASE WHEN sm.type='RETURN' THEN sm.quantity ELSE 0 END) AS total_return
    FROM stock_movements sm
    JOIN products p ON p.id = sm.product_id
    LEFT JOIN purchase_items pi ON pi.id = sm.purchase_item_id
    $where
    GROUP BY sm.product_id
    ORDER BY p.name ASC
    ";

    $res = $conn->query($sql);

    $html .= "<table>
        <tr>
            <th>Product</th>
            <th>Total IN</th>
            <th>Total OUT</th>
            <th>Total RETURN</th>
            <th>Balance</th>
        </tr>";

    while ($row = $res->fetch_assoc()) {
        $balance = ($row['total_in'] + $row['total_return']) - $row['total_out'];

        $html .= "<tr>
            <td>" . htmlspecialchars($row['product_name']) . "</td>
            <td>" . $row['total_in'] . "</td>
            <td>" . $row['total_out'] . "</td>
            <td>" . $row['total_return'] . "</td>
            <td>" . $balance . "</td>
        </tr>";
    }

    $html .= "</table>";
}

$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

$dompdf->stream("stock_movement_report.pdf", ["Attachment" => true]);
exit;
