<?php
$page_title = 'Edit Reject';
require_once('includes/load.php');
page_require_level(3);

$reject = find_reject_by_id((int)$_GET['id']);
if (!$reject) {
    $session->msg("d", "Reject not found!");
    redirect('reject_list.php');
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Proses update reject disini
    $id = (int)$_POST['reject_id'];
    $part_number = $db->escape($_POST['part_number']);
    $quantity = (int)$_POST['quantity'];
    $input_date = $db->escape($_POST['input_date']);
    $remark = $db->escape($_POST['remark']);

    $sql = "UPDATE reject_area SET part_number='{$part_number}', quantity={$quantity}, input_date='{$input_date}', remark='{$remark}' WHERE id={$id}";
    $result = $db->query($sql);

    if ($result && $db->affected_rows() === 1) {
        $session->msg("s", "Reject updated successfully!");
        redirect('reject_list.php', false);
    } else {
        $session->msg("d", "Failed to update reject.");
        redirect('edit_reject.php?id=' . (int)$id, false);
    }
}
?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>Edit Reject</strong>
            </div>
            <div class="panel-body">
                <form method="post" action="edit_reject.php?id=<?php echo (int)$reject['id']; ?>">
                    <div class="form-group">
                        <label for="part_number">Part Number</label>
                        <input type="text" class="form-control" name="part_number" value="<?php echo htmlspecialchars($reject['part_number']); ?>">
                    </div>
                    <div class="form-group">
                        <label for="quantity">Quantity</label>
                        <input type="number" class="form-control" name="quantity" value="<?php echo (int)$reject['quantity']; ?>">
                    </div>
                    <div class="form-group">
                        <label for="input_date">Input Date</label>
                        <input type="date" class="form-control" name="input_date" value="<?php echo $reject['input_date']; ?>">
                    </div>
                    <div class="form-group">
                        <label for="remark">Remark</label>
                        <input type="text" class="form-control" name="remark" value="<?php echo htmlspecialchars($reject['remark']); ?>">
                    </div>
                    <input type="hidden" name="reject_id" value="<?php echo (int)$reject['id']; ?>">
                    <button type="submit" class="btn btn-primary">Update</button>
                    <a href="reject_list.php" class="btn btn-default">Cancel</a>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include_once('layouts/footer.php'); ?>
