<?php
require_once '../includes/auth.php';
require_once '../db.php';

$draw   = $_POST['draw'] ?? 1;
$start  = $_POST['start'] ?? 0;
$length = $_POST['length'] ?? 25;
$search = $_POST['search']['value'] ?? "";

$from = $_POST['from'] ?? "";
$to   = $_POST['to'] ?? "";

$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 pi.batch_no LIKE '%$s%' OR sm.type LIKE '%$s%') ";
}

$totalRes = $conn->query("
    SELECT COUNT(*) AS total
    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
")->fetch_assoc();

$totalRecords = $totalRes['total'] ?? 0;

$sql = "
SELECT 
    sm.*,
    p.name AS product_name,
    pi.batch_no
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
LIMIT $start, $length
";

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

$data = [];
while ($row = $res->fetch_assoc()) {

    $ref = "-";
    if (!empty($row['reference_type']) && !empty($row['reference_id'])) {
        $refType = strtolower($row['reference_type']);
        $refLabel = strtoupper($row['reference_type']) . " #" . $row['reference_id'];
        $popupTypeMap = [
            'sale'            => 'sale',
            'purchase'        => 'purchase',
            'purchase_return' => 'pur_return',
            'sales_return'    => 'sal_return',
        ];
        if (isset($popupTypeMap[$refType])) {
            $pt = $popupTypeMap[$refType];
            $ref = '<a href="#" onclick="openDocPopup(\'' . $pt . '\',' . (int)$row['reference_id'] . ',\'' . addslashes($refLabel) . '\');return false;" style="color:#2563eb;text-decoration:none;">' . htmlspecialchars($refLabel) . '</a>';
        } else {
            $ref = htmlspecialchars($refLabel);
        }
    }

    $data[] = [
        "created_at"   => date("d-m-Y h:i A", strtotime($row['created_at'])),
        "product_name" => $row['product_name'],
        "batch_no"     => $row['batch_no'] ?? "-",
        "type"         => $row['type'],
        "quantity"     => $row['quantity'],
        "reference"    => $ref
    ];
}

echo json_encode([
    "draw" => intval($draw),
    "recordsTotal" => intval($totalRecords),
    "recordsFiltered" => intval($totalRecords),
    "data" => $data
]);
