<?php
$page_title = 'Transfer to Reject Area';
require_once('includes/load.php');
page_require_level(10);

function transfer_to_reject_area($part_number, $quantity, $notes = '') {
    global $db;

    // Clean and validate inputs
    $part_number = $db->escape(trim($part_number));
    $quantity = (int)$quantity;
    $notes = trim($notes);

    // Input validation
    if (empty($part_number)) {
        return ['status' => false, 'message' => 'Part number is required'];
    }
    if ($quantity === 0) {
        return ['status' => false, 'message' => 'Quantity cannot be zero'];
    }

    // Check if product exists
    $product = find_by_part_number('products', $part_number);
    if (!$product) {
        return ['status' => false, 'message' => 'Part number not found'];
    }

    // For positive quantities (moving to reject area), check stock availability
    if ($quantity > 0 && $product['quantity'] < $quantity) {
        return ['status' => false, 'message' => 'Insufficient stock'];
    }

    $db->begin_transaction();

    try {
        // 1. Update stock in products table (can increase or decrease)
        $sql = "UPDATE products SET quantity = quantity - {$quantity} 
                WHERE part_number = '{$part_number}'";
        if (!$db->query($sql)) {
            throw new Exception("Failed to update products: " . $db->error);
        }

        // 2. Update or insert into reject_area
        $reject_product = find_by_part_number('reject_area', $part_number);
        if ($reject_product) {
            // Check if the operation would make reject area quantity negative
            $new_reject_quantity = $reject_product['quantity'] + $quantity;
            if ($new_reject_quantity < 0) {
                throw new Exception("Cannot have negative quantity in reject area");
            }
            
            $sql = "UPDATE reject_area SET quantity = quantity + {$quantity} 
                    WHERE part_number = '{$part_number}'";
        } else {
            // If adding to reject area, quantity must be positive
            if ($quantity < 0) {
                throw new Exception("Cannot remove from empty reject area");
            }
            
            $sql = "INSERT INTO reject_area 
                    (part_number, name, quantity, buy_price, categorie_id, date) 
                    VALUES (
                        '{$db->escape($product['part_number'])}',
                        '{$db->escape($product['name'])}',
                        {$quantity},
                        '{$db->escape($product['buy_price'])}',
                        {$product['categorie_id']},
                        CURDATE()
                    )";
        }
        if (!$db->query($sql)) {
            throw new Exception("Failed to update reject area: " . $db->error);
        }

        // 3. Record transfer history - using correct table name reject_transfer_area
        $notes_sql = empty($notes) ? "NULL" : "'" . $db->escape($notes) . "'";
        $sql = "INSERT INTO reject_transfer_area 
                (part_number, quantity, notes, date) 
                VALUES (
                    '{$part_number}',
                    {$quantity},
                    {$notes_sql},
                    NOW()
                )";
        if (!$db->query($sql)) {
            throw new Exception("Failed to record transfer: " . $db->error);
        }

        $db->commit();
        return ['status' => true, 'message' => 'Transfer successful'];
    } catch (Exception $e) {
        $db->rollback();
        return ['status' => false, 'message' => 'Database error: ' . $e->getMessage()];
    }
}

// Handle form submission
if (isset($_POST['transfer'])) {
    $part_numbers = $_POST['part_number'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $notes = $_POST['notes'] ?? [];

    $success = true;
    $messages = [];

    foreach ($part_numbers as $index => $raw_part_number) {
        $part_number = trim($raw_part_number);
        $quantity = (int)($quantities[$index] ?? 0);
        $note = isset($notes[$index]) ? trim($notes[$index]) : '';

        if (empty($part_number)) {
            continue;
        }

        $result = transfer_to_reject_area($part_number, $quantity, $note);
        
        if (!$result['status']) {
            $success = false;
            $messages[] = "{$part_number}: {$result['message']}";
        }
    }

    if ($success && !empty($part_numbers)) {
        $session->msg('s', "Transfer completed successfully!");
    } elseif (!$success) {
        $session->msg('d', "Transfer failed:<br>- " . implode('<br>- ', $messages));
    } else {
        $session->msg('d', "No items to transfer");
    }
    
    redirect('transfer_reject.php', false);
}

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

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <h3 class="panel-title">Transfer Items to/from Reject Area</h3>
                <div class="pull-right">
                    <a href="list_transfer_reject.php" class="btn btn-info btn-xs">View Reject History</a>
                </div>
            </div>
            <div class="panel-body">
                <form method="post" action="transfer_reject.php" class="form" id="transferForm">
                    <div id="formInputs" class="mb-3">
                        <div class="form-group mb-2">
                            <div class="row">
                                <div class="col-md-4">
                                    <input type="text" class="form-control" name="part_number[]" placeholder="Part Number" required>
                                </div>
                                <div class="col-md-2">
                                    <input type="number" class="form-control" name="quantity[]" placeholder="Quantity" required>
                                    <small class="text-muted">Positive = to reject, Negative = from reject</small>
                                </div>
                                <div class="col-md-5">
                                    <input type="text" class="form-control" name="notes[]" placeholder="Notes/Reason">
                                </div>
                                <div class="col-md-1">
                                    <button type="button" class="btn btn-danger remove-btn">X</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <button type="button" class="btn btn-success mb-2" id="addMoreBtn">Add More Items</button>
                    <button type="submit" name="transfer" class="btn btn-primary">Process Transfer</button>
                </form>
                <br>
                <div class="message-container">
                    <?php echo display_msg($msg); ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Add more items
    document.getElementById('addMoreBtn').addEventListener('click', function() {
        const newInputGroup = document.createElement('div');
        newInputGroup.className = 'form-group mb-2';
        newInputGroup.innerHTML = `
            <div class="row">
                <div class="col-md-4">
                    <input type="text" class="form-control" name="part_number[]" placeholder="Part Number" required>
                </div>
                <div class="col-md-2">
                    <input type="number" class="form-control" name="quantity[]" placeholder="Quantity" required>
                    <small class="text-muted">Positive = to reject, Negative = from reject</small>
                </div>
                <div class="col-md-5">
                    <input type="text" class="form-control" name="notes[]" placeholder="Notes/Reason">
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-danger remove-btn">X</button>
                </div>
            </div>
        `;
        document.getElementById('formInputs').appendChild(newInputGroup);
    });

    // Remove item
    document.getElementById('formInputs').addEventListener('click', function(e) {
        if (e.target.classList.contains('remove-btn')) {
            const inputGroups = document.querySelectorAll('#formInputs .form-group');
            if (inputGroups.length > 1) {
                e.target.closest('.form-group').remove();
            } else {
                alert('You need at least one item');
            }
        }
    });
});
</script>

<style>
.message-container {
    margin-top: 20px;
    padding: 10px;
    border-radius: 4px;
}
.btn {
    padding: 6px 12px;
}
.remove-btn {
    width: 100%;
}
.form-control {
    margin-bottom: 5px;
}
.text-muted {
    font-size: 0.8em;
    color: #6c757d;
}
</style>

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