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

// Start session early
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Fetch OS numbers for dropdown
$os_result = $conn->query("
    SELECT o.os_number 
    FROM outward_stock o
    ORDER BY o.id DESC
");

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $return_date     = $_POST['return_date'];
    $os_number       = $_POST['os_number'];
    $given_to        = $_POST['given_to'];
    $purchase_id     = (int)$_POST['purchase_stock_id']; // hidden field
    $item_name       = $_POST['item_name'];
    $particular_name = $_POST['particular_name'];
    $specification   = $_POST['specification'];
    $model_number    = $_POST['model_number'];
    $qty             = (int)$_POST['qty'];
    $status          = $_POST['status'];
    $remarks         = $_POST['remarks'];

    // Step 1: Always reduce outward_stock
    $getOutward = "
        SELECT id, qty 
        FROM outward_stock 
        WHERE os_number = '$os_number' 
          AND purchase_stock_id = $purchase_id
        LIMIT 1
    ";
    $outwardRes = $conn->query($getOutward);

    if ($outwardRes && $outwardRes->num_rows > 0) {
        $outwardRow = $outwardRes->fetch_assoc();
        $outwardId  = $outwardRow['id'];
        $outwardQty = (int)$outwardRow['qty'];

        if ($qty < $outwardQty) {
            $conn->query("UPDATE outward_stock SET qty = qty - $qty WHERE id = $outwardId");
        } else {
            $conn->query("DELETE FROM outward_stock WHERE id = $outwardId");
        }
    }

    // Step 2: If Not OK, log in fault_stock + update purchase_stock
    if ($status === 'Not OK') {
        // $username = ucfirst(htmlspecialchars($_SESSION['username'] ?? 'User'));
        $sql = "
            INSERT INTO fault_stock 
            (fault_date, given_to, purchase_stock_id, item_name, particular_name, specification, model_number, qty, remarks, company_name)
            VALUES 
            ('$return_date', '$given_to', $purchase_id, '$item_name', '$particular_name', '$specification', '$model_number', $qty, '$remarks', 'Nilatech')
        ";
        $conn->query($sql);

        $updateFault = "
            UPDATE purchase_stock 
            SET fault_count = IFNULL(fault_count, 0) + $qty 
            WHERE id = $purchase_id
            LIMIT 1
        ";
        $conn->query($updateFault);
    }

    // Redirect to inventory page
    header("Location: inventory.php");
    exit();
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Return Product</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">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <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 include 'navbar.php'; ?>

<div class="flex-grow-1">
    <div class="container mt-2">
        <h2 class="text-center text-success mb-4">Return of Products</h2>

        <form method="POST" class="row g-3 shadow p-4 bg-white rounded">
            <div class="col-md-4">
                <label class="form-label">Return Date</label>
                <input type="date" class="form-control" name="return_date" required>
            </div>

            <div class="col-md-4">
                <label class="form-label">OS Number</label>
                <select class="form-select" name="os_number" id="os_number" required>
                    <option value="">-- Select OS Number --</option>
                    <?php while($row = $os_result->fetch_assoc()) {
                        echo "<option value='{$row['os_number']}'>{$row['os_number']}</option>";
                    } ?>
                </select>
            </div>

            <div class="col-md-4">
                <label class="form-label">Given To</label>
                <input type="text" class="form-control" name="given_to" id="given_to" readonly required>
            </div>

            <div class="col-md-4">
                <label class="form-label">Item Name</label>
                <input type="text" class="form-control" name="item_name" id="item_name" readonly required>
            </div>

            <div class="col-md-4">
                <label class="form-label">Particular Name</label>
                <input type="text" class="form-control" name="particular_name" id="particular_name" readonly required>
            </div>

            <div class="col-md-4">
                <label class="form-label">Specification</label>
                <input type="text" class="form-control" name="specification" id="specification" readonly required>
            </div>

            <div class="col-md-4">
                <label class="form-label">Model Number</label>
                <input type="text" class="form-control" name="model_number" id="model_number" readonly required>
            </div>

            <div class="col-md-4">
                <label class="form-label">Quantity</label>
                <input type="number" class="form-control" name="qty" id="qty" min="1" required>
            </div>

            <div class="col-md-4">
                <label class="form-label">Status</label>
                <select class="form-select" name="status" required>
                    <option value="">-- Select Status --</option>
                    <option value="OK">OK</option>
                    <option value="Not OK">Not OK</option>
                </select>
            </div>

            <div class="col-md-4">
                <label class="form-label">Remarks</label>
                <input type="text" class="form-control" name="remarks" id="remarks">
            </div>

            <!-- hidden purchase_stock_id -->
            <input type="hidden" name="purchase_stock_id" id="purchase_stock_id">

            <div class="col-12 text-center">
                <button type="submit" class="btn btn-success">Process Return</button>
            </div>
        </form>
    </div>
</div>

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

<script>
$(document).ready(function(){
    $('#os_number').change(function(){
        var os_number = $(this).val();
        if(os_number !== '') {
            $.post('get_outward_by_os.php', {os_number: os_number}, function(data){
                var obj = JSON.parse(data);
                $('#item_name').val(obj.item_name);
                $('#particular_name').val(obj.particular_name);
                $('#specification').val(obj.specification);
                $('#model_number').val(obj.model_number);
                $('#qty').val(obj.qty);
                $('#given_to').val(obj.given_to);
                $('#remarks').val(obj.remarks);
                $('#purchase_stock_id').val(obj.purchase_stock_id);
            });
        }
    });
});
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
