<?php
include 'db.php';
include 'auth_check.php';

// Handle filters
$filter_item = isset($_GET['item_name']) ? $_GET['item_name'] : '';
$filter_given_to = isset($_GET['given_to']) ? $_GET['given_to'] : '';
$filter_date = isset($_GET['outward_date']) ? $_GET['outward_date'] : '';

// Pagination variables
$limit = 10; 
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if($page < 1) $page = 1;
$start = ($page - 1) * $limit;

// Base SQL query with join
$sql = "
    SELECT 
        o.*,
        p.invoice_number,
        p.item_name,
        p.particular_name,
        p.specification,
        p.model_number
    FROM outward_stock o
    LEFT JOIN purchase_stock p ON o.purchase_stock_id = p.id
    WHERE 1
";

// Filters
if ($filter_item != '') {
    $sql .= " AND p.item_name LIKE '%".$conn->real_escape_string($filter_item)."%'";
}
if ($filter_given_to != '') {
    $sql .= " AND o.given_to LIKE '%".$conn->real_escape_string($filter_given_to)."%'";
}
if ($filter_date != '') {
    $sql .= " AND o.outward_date = '".$conn->real_escape_string($filter_date)."'";
}

// Count total records
$totalResult = $conn->query($sql);
$totalRecords = $totalResult->num_rows;
$totalPages = ceil($totalRecords / $limit);

// Add ORDER + LIMIT
$sql .= " ORDER BY o.id DESC LIMIT $start, $limit";
$result = $conn->query($sql);
?>

<!DOCTYPE html>
<html>
<head>
    <title>Outward Stock View</title>
    <link rel="icon" type="image/png" href="assets/logo/logo_icon.png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { display: flex; flex-direction: column; min-height: 100vh; }
        .flex-grow-1 { flex: 1; }
        footer { background: #f8f9fa; padding: 10px 0; }
    </style>
</head>
<body class="bg-light">

<?php
if (session_status() == PHP_SESSION_NONE) session_start();
include 'navbar.php';
?>

<div class="flex-grow-1">
    <div class="container mt-2">
        <h2 class="mb-4 text-center text-success">Outward Stock View</h2>
        <div class="d-flex justify-content-center">
            <!-- Filter Form -->
            <form method="GET" class="row g-3 mb-4">
                <div class="col-md-3">
                    <input type="text" class="form-control" name="item_name" placeholder="Filter by Item" value="<?php echo htmlspecialchars($filter_item); ?>">
                </div>
                <div class="col-md-3">
                    <input type="text" class="form-control" name="given_to" placeholder="Filter by Given To" value="<?php echo htmlspecialchars($filter_given_to); ?>">
                </div>
                <div class="col-md-3">
                    <input type="date" class="form-control" name="outward_date" value="<?php echo htmlspecialchars($filter_date); ?>">
                </div>
                <div class="col-md-3 d-flex gap-2">
                    <button class="btn btn-success" type="submit">Filter</button>
                    <a href="outward_view.php" class="btn btn-secondary">Reset</a>
                </div>
            </form>
        </div>

        <!-- Outward Table -->
        <table class="table table-bordered table-striped shadow-sm">
            <thead class="table-dark text-center">
                <tr>
                    <th>OS Number</th>
                    <th>Invoice</th>
                    <th>Outward Date</th>
                    <th>Given To</th>
                    <th>Item</th>
                    <th>Particular</th>
                    <th>Specification</th>
                    <th>Model</th>
                    <th>Qty</th>
                    <th>Remarks</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                if ($result && $result->num_rows > 0):
                    while ($row = $result->fetch_assoc()):
                ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['os_number']); ?></td>
                    <td><?php echo htmlspecialchars($row['invoice_number'] ?? 'N/A'); ?></td>
                    <td><?php echo htmlspecialchars($row['outward_date']); ?></td>
                    <td><?php echo htmlspecialchars($row['given_to']); ?></td>
                    <td><?php echo htmlspecialchars($row['item_name']); ?></td>
                    <td><?php echo htmlspecialchars($row['particular_name']); ?></td>
                    <td><?php echo htmlspecialchars($row['specification']); ?></td>
                    <td><?php echo htmlspecialchars($row['model_number']); ?></td>
                    <td><?php echo (int)$row['qty']; ?></td>
                    <td><?php echo htmlspecialchars($row['remarks']); ?></td>
                    <td class="text-center">
                        <a href="edit_outward.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning">Edit</a>
                        <a href="#" 
                        class="btn btn-sm btn-danger delete-btn"
                        data-id="<?php echo $row['id']; ?>"
                        data-os="<?php echo htmlspecialchars($row['os_number']); ?>"
                        data-date="<?php echo htmlspecialchars($row['outward_date']); ?>"
                        data-given="<?php echo htmlspecialchars($row['given_to']); ?>"
                        data-item="<?php echo htmlspecialchars($row['item_name']); ?>"
                        data-qty="<?php echo (int)$row['qty']; ?>"
                        data-invoice="<?php echo htmlspecialchars($row['invoice_number'] ?? 'N/A'); ?>">
                        Delete
                        </a>
                    </td>
                </tr>
                <?php
                    endwhile;
                else:
                    echo "<tr><td colspan='11' class='text-center text-danger'>No records found</td></tr>";
                endif;
                ?>
            </tbody>
        </table>

        <!-- Pagination -->
        <?php if($totalPages > 1): ?>
        <div class="d-flex justify-content-center mt-3">
            <ul class="pagination">
                <li class="page-item <?php if($page <= 1) echo 'disabled'; ?>">
                    <a class="page-link" href="?page=<?php echo max($page-1,1); ?>&item_name=<?php echo urlencode($filter_item); ?>&given_to=<?php echo urlencode($filter_given_to); ?>&outward_date=<?php echo urlencode($filter_date); ?>">Previous</a>
                </li>
                <?php for ($i=1; $i<=$totalPages; $i++): ?>
                    <li class="page-item <?php if($page==$i) echo 'active'; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>&item_name=<?php echo urlencode($filter_item); ?>&given_to=<?php echo urlencode($filter_given_to); ?>&outward_date=<?php echo urlencode($filter_date); ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>
                <li class="page-item <?php if($page >= $totalPages) echo 'disabled'; ?>">
                    <a class="page-link" href="?page=<?php echo min($page+1,$totalPages); ?>&item_name=<?php echo urlencode($filter_item); ?>&given_to=<?php echo urlencode($filter_given_to); ?>&outward_date=<?php echo urlencode($filter_date); ?>">Next</a>
                </li>
            </ul>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php
if (session_status() == PHP_SESSION_NONE) session_start();
include 'footer.php';
?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const deleteButtons = document.querySelectorAll('.delete-btn');

    deleteButtons.forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();

            const id = this.dataset.id;
            const os = this.dataset.os;
            const date = this.dataset.date;
            const given = this.dataset.given;
            const item = this.dataset.item;
            const qty = this.dataset.qty;
            const invoice = this.dataset.invoice;

            const confirmMsg = `Are you sure you want to delete this record?\n\n` +
                               `OS Number: ${os}\n` +
                               `Invoice: ${invoice}\n` +
                               `Outward Date: ${date}\n` +
                               `Given To: ${given}\n` +
                               `Item: ${item}\n` +
                               `Qty: ${qty}`;

            if (!confirm(confirmMsg)) return;

            fetch('delete_outward_ajax.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({id: id})
            })
            .then(response => response.json())
            .then(data => {
                if(data.success) {
                    btn.closest('tr').remove();
                } else {
                    alert('Error deleting record: ' + data.error);
                }
            })
            .catch(err => alert('AJAX error: ' + err));
        });
    });
});
</script>

</body>
</html>
