<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

$search = trim($_GET['search'] ?? '');
$type = trim($_GET['type'] ?? '');
$fromDate = trim($_GET['from_date'] ?? '');
$toDate = trim($_GET['to_date'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));

$allowedLimits = [10, 25, 50, 100];
$limit = (int)($_GET['limit'] ?? 10);

if (!in_array($limit, $allowedLimits)) {
    $limit = 10;
}

$offset = ($page - 1) * $limit;

/*
    WHERE builder
*/
$where = [];
$params = [];

/*
    Search filter
*/
if (!empty($search)) {
    $where[] = "(i.name LIKE ? OR i.barcode LIKE ? OR se.reference LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

/*
    Type filter
*/
if (!empty($type)) {
    $where[] = "se.type = ?";
    $params[] = $type;
}

/*
    Date filters
*/
if (!empty($fromDate)) {
    $where[] = "se.stock_date >= ?";
    $params[] = $fromDate;
}

if (!empty($toDate)) {
    $where[] = "se.stock_date <= ?";
    $params[] = $toDate;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = ' WHERE ' . implode(' AND ', $where);
}

/*
    COUNT QUERY
*/
$countSql = "
    SELECT COUNT(*)
    FROM stock_entries se
    INNER JOIN items i ON se.item_id = i.id
    $whereSql
";

$stmt = $db->prepare($countSql);
$stmt->execute($params);
$totalRecords = $stmt->fetchColumn();

$totalPages = ceil($totalRecords / $limit);

/*
    DATA QUERY
*/
$dataSql = "
    SELECT
        se.*,
        i.name AS item_name,
        i.barcode,
        u.name AS unit_name
    FROM stock_entries se
    INNER JOIN items i ON se.item_id = i.id
    LEFT JOIN units u ON se.unit_id = u.id
    $whereSql
    ORDER BY se.created_at DESC
    LIMIT $limit OFFSET $offset
";

$stmt = $db->prepare($dataSql);
$stmt->execute($params);

$entries = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="card shadow-sm">
    <div class="card-body table-responsive">

        <table class="table table-bordered table-hover align-middle">

            <thead class="table-dark">
                <tr>
                    <th>ID</th>
                    <th>Stock Date</th>
                    <th>Created</th>
                    <th>Item</th>
                    <th>Barcode</th>
                    <th>Type</th>
                    <th>Qty</th>
                    <th>Unit</th>
                    <th>Rate</th>
                    <th>Total</th>
                    <th>Reference</th>
                    <th>Remarks</th>
                </tr>
            </thead>

            <tbody>

            <?php if (empty($entries)): ?>
                <tr>
                    <td colspan="12" class="text-center">
                        No stock history found.
                    </td>
                </tr>
            <?php endif; ?>

            <?php foreach ($entries as $entry): ?>

                <?php
                $badgeClass = $entry['type'] === 'IN'
                    ? 'bg-success'
                    : 'bg-warning';
                ?>

                <tr>
                    <td><?= $entry['id'] ?></td>

                    <td>
                        <?= !empty($entry['stock_date'])
                            ? date('d-m-Y', strtotime($entry['stock_date']))
                            : '' ?>
                    </td>

                    <td>
                        <?= date(
                            'd-m-Y h:i A',
                            strtotime($entry['created_at'])
                        ) ?>
                    </td>

                    <td><?= htmlspecialchars($entry['item_name']) ?></td>

                    <td><?= htmlspecialchars($entry['barcode']) ?></td>

                    <td>
                        <span class="badge <?= $badgeClass ?>">
                            <?= htmlspecialchars($entry['type']) ?>
                        </span>
                    </td>

                    <td><?= number_format((float)$entry['qty'], 2) ?></td>

                    <td><?= htmlspecialchars($entry['unit_name'] ?? '') ?></td>

                    <td>₹ <?= number_format((float)$entry['rate'], 2) ?></td>

                    <td>₹ <?= number_format((float)$entry['total'], 2) ?></td>

                    <td><?= htmlspecialchars($entry['reference']) ?></td>

                    <td><?= htmlspecialchars($entry['remarks']) ?></td>
                </tr>

            <?php endforeach; ?>

            </tbody>

        </table>

        <!-- PAGINATION -->
        <?php if ($totalPages > 1): ?>
            <nav>
                <ul class="pagination justify-content-center">

                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <button
                                class="page-link"
                                onclick="loadHistory(<?= $page - 1 ?>)"
                            >
                                Previous
                            </button>
                        </li>
                    <?php endif; ?>

                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                        <li class="page-item <?= $page == $i ? 'active' : '' ?>">
                            <button
                                class="page-link"
                                onclick="loadHistory(<?= $i ?>)"
                            >
                                <?= $i ?>
                            </button>
                        </li>
                    <?php endfor; ?>

                    <?php if ($page < $totalPages): ?>
                        <li class="page-item">
                            <button
                                class="page-link"
                                onclick="loadHistory(<?= $page + 1 ?>)"
                            >
                                Next
                            </button>
                        </li>
                    <?php endif; ?>

                </ul>
            </nav>
        <?php endif; ?>

    </div>
</div>