<?php
require_once __DIR__ . '/../../classes/Disposal.php';
require_once __DIR__ . '/../../classes/Inventory.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);
$inventory = new Inventory($conn, $logger);
$isAdmin = $auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id']);
$branchId = $isAdmin ? null : $auth->getUserBranch($_SESSION['user_id']);
$itemsSql = "SELECT item_id, unique_code, item_name, item_details, shelf_status, current_location_id
             FROM items
             WHERE item_id NOT IN (SELECT item_id FROM sold_items WHERE item_id IS NOT NULL)
               AND shelf_status <> 'disposed'";
$itemsParams = [];
if ($branchId !== null) {
    $itemsSql .= " AND current_location_id = :branch_id";
    $itemsParams[':branch_id'] = (int)$branchId;
}
$itemsSql .= " ORDER BY item_name ASC, unique_code ASC";
$itemsStmt = $conn->prepare($itemsSql);
$itemsStmt->execute($itemsParams);
$items = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $itemId = (int)($_POST['item_id'] ?? 0);
    $item = $itemId ? $inventory->getItemById($itemId) : null;
    if (!$item) {
        $error = 'Please select a valid item.';
    } else {
        $data = [
            'item_id' => $itemId,
            'branch_id' => $item['current_location_id'] ?? $branchId,
            'reason' => $_POST['reason'] ?? 'other',
            'condition_notes' => trim($_POST['condition_notes'] ?? ''),
            'estimated_value' => $_POST['estimated_value'] ?? 0,
            'disposal_method' => trim($_POST['disposal_method'] ?? ''),
            'requested_by' => $_SESSION['user_id']
        ];
        $id = $disposal->createRequest($data);
        header('Location: index.php?success=' . urlencode("Disposal request #{$id} submitted for approval."));
        exit;
    }
}
?>

<div class="container mt-4 mb-5">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h2 class="mb-1">New Disposal Request</h2>
            <p class="text-muted mb-0">Submit an item for approval before final disposal.</p>
        </div>
        <a href="index.php" class="btn btn-secondary">Back</a>
    </div>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <div class="card">
        <div class="card-body">
            <form method="POST" class="row g-3">
                <div class="col-md-6">
                    <label class="form-label">Item</label>
                    <select name="item_id" class="form-select" required>
                        <option value="">Select item</option>
                        <?php foreach ($items as $item): ?>
                            <option value="<?php echo (int)$item['item_id']; ?>">
                                <?php echo htmlspecialchars(($item['unique_code'] ?? '') . ' - ' . ($item['item_name'] ?? 'Unknown item') . ' - ' . ($item['item_details'] ?? 'N/A') . ' (' . ($item['shelf_status'] ?? 'unknown') . ')'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Reason</label>
                    <select name="reason" class="form-select" required>
                        <option value="obsolete">Obsolete</option>
                        <option value="damaged">Damaged</option>
                        <option value="written_off">Written off</option>
                        <option value="lost">Lost</option>
                        <option value="other">Other</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Estimated Value</label>
                    <input type="number" step="0.01" min="0" name="estimated_value" class="form-control" value="0">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Proposed Disposal Method</label>
                    <input type="text" name="disposal_method" class="form-control" placeholder="Write-off, recycle, parts recovery, discard">
                </div>
                <div class="col-12">
                    <label class="form-label">Condition Notes</label>
                    <textarea name="condition_notes" rows="5" class="form-control" required></textarea>
                </div>
                <div class="col-12">
                    <button class="btn btn-primary">Submit for Approval</button>
                </div>
            </form>
        </div>
    </div>
</div>

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