<?php
$page_title = 'Update BOM Level';
require_once('includes/load.php');
page_require_level(2);

// Handle bulk update submission
if(isset($_POST['bulk_update'])) {
    $updated = 0;
    $errors = array();
    
    foreach($_POST['levels'] as $id => $level) {
        $id = (int)$db->escape($id);
        $level = $db->escape($level);
        
        if(!empty($level)) {
            $sql = "UPDATE bom_level SET level = '{$level}' WHERE id = '{$id}'";
            $result = $db->query($sql);
            
            if($db->affected_rows() === 1) {
                $updated++;
            } else {
                $errors[] = "Failed to update BOM ID {$id}";
            }
        }
    }
    
    if($updated > 0) {
        $session->msg('s', "Successfully updated {$updated} BOM levels.");
    }
    if(!empty($errors)) {
        $session->msg('d', implode("<br>", $errors));
    }
    redirect('update_bom_level.php?search='.urlencode($_POST['search']), false);
}

// Initialize empty array for BOMs
$boms = array();
$search_term = '';

// Handle search functionality
if (isset($_GET['search']) || (isset($_POST['search']) && !empty($_POST['search']))) {
    $search_term = isset($_GET['search']) ? $_GET['search'] : $_POST['search'];
    $search = $db->escape($search_term);
    $sql = "SELECT bl.*, 
                   p1.new_code AS parent_new_code, 
                   p2.new_code AS child_new_code, 
                   p2.uom AS uom
            FROM bom_level bl
            LEFT JOIN products p1 ON bl.parent_bom = p1.part_number
            LEFT JOIN products p2 ON bl.child_bom = p2.part_number
            WHERE bl.parent_bom LIKE '%$search%'
            OR bl.child_bom LIKE '%$search%'
            OR p1.new_code LIKE '%$search%'
            OR p2.new_code LIKE '%$search%'
            OR p2.uom LIKE '%$search%'
            OR bl.level LIKE '%$search%'";
    $boms = find_by_sql($sql);
}

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

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <strong>
                    <span class="glyphicon glyphicon-th"></span>
                    <span>Update BOM Level</span>
                </strong>
            </div>
            <div class="panel-body">
                <!-- Search Form -->
                <form method="get" action="update_bom_level.php" class="form-inline mb-3">
                    <div class="form-group">
                        <label for="search" class="sr-only">Search</label>
                        <input type="text" class="form-control" id="search" name="search" 
                               placeholder="Search BOM" required 
                               value="<?php echo htmlspecialchars($search_term); ?>">
                    </div>
                    <button type="submit" class="btn btn-primary">Search</button>
                </form>
                
                <?php if(!empty($search_term)): ?>
                <form method="post" action="update_bom_level.php">
                <input type="hidden" name="search" value="<?php echo htmlspecialchars($search_term); ?>">
                <div class="table-responsive">
                    <table class="table table-striped table-bordered table-hover">
                        <thead>
                            <tr>
                                <th class="text-center" style="width: 5%;"> # </th>
                                <th> Parent BOM </th>
                                <th> Parent Code </th>
                                <th> Child BOM </th>
                                <th> Child Code </th>
                                <th> Qty </th>
                                <th> UOM </th>
                                <th> Current Level </th>
                                <th> New Level </th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(!empty($boms)): ?>
                                <?php foreach ($boms as $bom): ?>
                                <tr>
                                    <td class="text-center"><?php echo $bom['id']; ?></td>
                                    <td><?php echo htmlspecialchars($bom['parent_bom']); ?></td>
                                    <td><?php echo htmlspecialchars($bom['parent_new_code']); ?></td>
                                    <td><?php echo htmlspecialchars($bom['child_bom']); ?></td>
                                    <td><?php echo htmlspecialchars($bom['child_new_code']); ?></td>
                                    <td><?php echo $bom['qty']; ?></td>
                                    <td><?php echo htmlspecialchars($bom['uom']); ?></td>
                                    <td><?php echo htmlspecialchars($bom['level']); ?></td>
                                    <td>
                                        <input type="text" class="form-control" 
                                               name="levels[<?php echo $bom['id']; ?>]" 
                                               value="<?php echo htmlspecialchars($bom['level']); ?>">
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="9" class="text-center">No matching BOM records found</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <?php if(!empty($boms)): ?>
                <div class="form-group pull-right">
                    <button type="submit" name="bulk_update" class="btn btn-success">
                        <i class="glyphicon glyphicon-floppy-disk"></i> Update All
                    </button>
                </div>
                <?php endif; ?>
                </form>
                <?php elseif(empty($search_term)): ?>
                    <div class="alert alert-info">Please enter a search term to display BOM records</div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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