<?php
require_once __DIR__ . '/../../classes/Disposal.php';
require_once __DIR__ . '/../../classes/Logger.php';
include '../../includes/header.php';

$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
$disposal = new Disposal($conn, $logger);
$isAdmin = $auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id']);
$branchId = $isAdmin ? null : $auth->getUserBranch($_SESSION['user_id']);
$requests = $disposal->getRequests($branchId);
$selectedId = isset($_GET['audit']) ? (int)$_GET['audit'] : 0;
$audit = $selectedId ? $disposal->getAudit($selectedId) : [];
?>

<div class="container mt-4 mb-5">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h2 class="mb-1">Inventory Disposals</h2>
            <p class="text-muted mb-0">Document obsolete, damaged, and written-off inventory items.</p>
        </div>
        <a href="create.php" class="btn btn-primary"><i class="fas fa-plus"></i> New Disposal</a>
    </div>

    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($_GET['success']); ?></div>
    <?php endif; ?>

    <div class="card">
        <div class="card-body table-responsive">
            <table class="table table-striped align-middle" id="disposalsTable">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Item</th>
                        <th>Branch</th>
                        <th>Reason</th>
                        <th>Status</th>
                        <th>Requested</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($requests as $request): ?>
                        <tr>
                            <td><?php echo (int)$request['disposal_id']; ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($request['item_name'] ?? 'Unknown item'); ?></strong><br>
                                <small class="text-muted"><?php echo htmlspecialchars($request['unique_code'] ?? ''); ?></small><br><small>Details: <?php echo htmlspecialchars($request['item_details'] ?? 'N/A'); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($request['branch_name'] ?? 'N/A'); ?></td>
                            <td><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $request['reason']))); ?></td>
                            <td><span class="badge bg-secondary"><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $request['status']))); ?></span></td>
                            <td><?php echo htmlspecialchars($request['requested_at']); ?><br><small><?php echo htmlspecialchars($request['requested_by_name'] ?? ''); ?></small></td>
                            <td>
                                <a class="btn btn-sm btn-outline-info" href="?audit=<?php echo (int)$request['disposal_id']; ?>">Audit</a>
                                <?php if ($isAdmin && $request['status'] === 'pending'): ?>
                                    <form method="POST" action="action.php" class="d-inline">
                                        <input type="hidden" name="disposal_id" value="<?php echo (int)$request['disposal_id']; ?>">
                                        <input type="hidden" name="status" value="approved">
                                        <button class="btn btn-sm btn-success" onclick="return confirm('Approve this disposal request?')">Approve</button>
                                    </form>
                                    <form method="POST" action="action.php" class="d-inline">
                                        <input type="hidden" name="disposal_id" value="<?php echo (int)$request['disposal_id']; ?>">
                                        <input type="hidden" name="status" value="rejected">
                                        <button class="btn btn-sm btn-danger" onclick="return confirm('Reject this disposal request?')">Reject</button>
                                    </form>
                                <?php endif; ?>
                                <?php if ($isAdmin && $request['status'] === 'approved'): ?>
                                    <form method="POST" action="action.php" class="d-inline">
                                        <input type="hidden" name="disposal_id" value="<?php echo (int)$request['disposal_id']; ?>">
                                        <input type="hidden" name="status" value="completed">
                                        <button class="btn btn-sm btn-dark" onclick="return confirm('Mark this item as fully disposed?')">Complete</button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if ($selectedId): ?>
        <div class="card mt-4">
            <div class="card-header"><strong>Audit Trail for Disposal #<?php echo $selectedId; ?></strong></div>
            <div class="card-body">
                <?php if (!$audit): ?>
                    <p class="text-muted mb-0">No audit entries found.</p>
                <?php else: ?>
                    <ul class="list-group">
                        <?php foreach ($audit as $entry): ?>
                            <li class="list-group-item">
                                <strong><?php echo htmlspecialchars(ucfirst($entry['action'])); ?></strong>
                                by <?php echo htmlspecialchars($entry['username'] ?? 'Unknown'); ?>
                                <span class="text-muted"><?php echo htmlspecialchars($entry['performed_at']); ?></span><br>
                                <?php echo nl2br(htmlspecialchars($entry['notes'] ?? '')); ?>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
    new DataTable('#disposalsTable');
</script>

<?php include '../../includes/footer.php'; ?>
