<?php
$page_title = 'Delivery Material';
require_once('includes/sql.php');
page_require_level(3);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $requestId = (int) $_POST['requestId'];
    $deliveryQuantity = (int) $_POST['deliveryQuantity'];

    // Fetch request details from request_material
    $sql_request = "SELECT rm.id, rm.request_number, rm.product_id, rm.requested_quantity, p.part_number
                    FROM request_material rm
                    LEFT JOIN products p ON rm.product_id = p.id
                    WHERE rm.id = '{$requestId}' AND rm.status = 'pending'";
    
    $result_request = $db->query($sql_request);

    if ($result_request->num_rows == 0) {
        $session->msg('d', 'Material request not found or already processed.');
        redirect('delivery_material.php', false);
    } else {
        $row_request = $result_request->fetch_assoc();
        $request_number = $row_request['request_number'];
        $product_id = $row_request['product_id'];
        $part_number = $row_request['part_number'];
        $requested_quantity = $row_request['requested_quantity'];

        // Validate delivery quantity
        if ($deliveryQuantity <= 0) {
            $session->msg('d', 'Invalid delivery quantity.');
            redirect('delivery_material.php', false);
        } elseif ($deliveryQuantity > $requested_quantity) {
            $session->msg('d', 'Delivery quantity cannot exceed requested quantity.');
            redirect('delivery_material.php', false);
        }

        // Insert into delivery_material table
        $sql_insert = "INSERT INTO delivery_material (request_id, request_number, product_id, part_number, delivery_quantity, delivery_date)
                       VALUES ('{$requestId}', '{$request_number}', '{$product_id}', '{$part_number}', '{$deliveryQuantity}', NOW())";

        if ($db->query($sql_insert)) {
            // Update request_material status if fully delivered
            if ($deliveryQuantity == $requested_quantity) {
                $sql_update = "UPDATE request_material SET status = 'approved', approve_date = NOW() WHERE id = '{$requestId}'";
                $db->query($sql_update);
            }

            $session->msg('s', 'Material delivery recorded successfully.');
            redirect('delivery_material.php', false);
        } else {
            $session->msg('d', 'Failed to record delivery: ' . $db->error);
            redirect('delivery_material.php', false);
        }
    }
}

// Fetch pending request materials with outstanding delivery
$sql = "SELECT rm.id, p.part_number, p.name, rm.requested_quantity, rm.request_date 
        FROM request_material rm 
        LEFT JOIN products p ON rm.product_id = p.id 
        WHERE rm.status = 'pending'
        AND rm.requested_quantity > (
            SELECT IFNULL(SUM(dm.delivery_quantity), 0)
            FROM delivery_material dm
            WHERE dm.request_id = rm.id
        )";

$result = $db->query($sql);
?>

<?php include_once('layouts/header.php'); ?>
<div class="row">
    <div class="col-md-12">
        <h2>Delivery Material</h2>
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Request ID</th>
                    <th>Product Part Number</th>
                    <th>Product Name</th>
                    <th>Requested Quantity</th>
                    <th>Request Date</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($row = $result->fetch_assoc()) : ?>
                    <tr>
                        <td><?php echo $row['id']; ?></td>
                        <td><?php echo $row['part_number']; ?></td>
                        <td><?php echo $row['name']; ?></td>
                        <td><?php echo $row['requested_quantity']; ?></td>
                        <td><?php echo $row['request_date']; ?></td>
                        <td>
                            <form method="post">
                                <input type="hidden" name="requestId" value="<?php echo $row['id']; ?>">
                                <div class="form-group">
                                    <label for="deliveryQuantity">Delivery Quantity:</label>
                                    <input type="number" class="form-control" name="deliveryQuantity" required>
                                </div>
                                <button type="submit" class="btn btn-primary">Record Delivery</button>
                            </form>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

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