<?php
/**
 * modules/menue/add_menue.php - WIMAS Component Architecture
 */

// =========================================================================
// 1. AJAX GET HANDLER (Calculates next order for child pages)
// =========================================================================
if (isset($_GET['get_order']) && isset($_GET['mid'])) {
    ob_clean(); 
    $mid = (int)$_GET['mid'];
    $sql = "SELECT MAX(SORT_ORDER) as max_order FROM TBL_CHILD_MENU WHERE MAIN_MENU_ID = $mid";
    $res = $db->query($sql);
    $row = mysqli_fetch_assoc($res);
    echo ($row['max_order'] ? $row['max_order'] + 1 : 1);
    exit;
}

// =========================================================================
// 2. FORM POST HANDLER (PRG Pattern: Post -> Redirect -> Get)
// =========================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $menu_type = $_POST['menu_type'];
    $created_by = (int)$_SESSION['user_id'];

    if ($menu_type === 'parent') {
        $parent_name = $db->escape($_POST['parent_name']);
        $parent_icon = $db->escape($_POST['parent_icon']);
        $sort_order  = (int)$_POST['parent_order'];
        $status      = $db->escape($_POST['parent_status']);

        $sql = "INSERT INTO TBL_MAIN_MENU (MENU_NAME, MENU_ICON, SORT_ORDER, STATUS, CREATED_BY) 
                VALUES ('$parent_name', '$parent_icon', $sort_order, '$status', $created_by)";
        
        if ($db->query($sql)) {
            // CRITICAL: This redirect stops the refresh/duplicate issue!
            header("Location: index.php?s=" . encrypt_url('mod=menue&page=add_menue') . "&status=added");
            exit;
        }

    } else if ($menu_type === 'child') {
        $main_menu_id = (int)$_POST['main_menu_id'];
        $child_name   = $db->escape($_POST['child_name']);
        $module_name  = $db->escape($_POST['module_name']);
        $page_name    = $db->escape($_POST['page_name']);
        $sort_order   = (int)$_POST['child_order'];
        $status       = $db->escape($_POST['child_status']);

        $menu_url = "mod=" . $module_name . "&page=" . $page_name;

        $sql = "INSERT INTO TBL_CHILD_MENU (MAIN_MENU_ID, MENU_NAME, MODULE_NAME, MENU_URL, MENU_ICON, SORT_ORDER, STATUS, CREATED_BY) 
                VALUES ($main_menu_id, '$child_name', '$module_name', '$menu_url', 'far fa-circle', $sort_order, '$status', $created_by)";
        
        if ($db->query($sql)) {
            // CRITICAL: This redirect stops the refresh/duplicate issue!
            header("Location: index.php?s=" . encrypt_url('mod=menue&page=add_menue') . "&status=added");
            exit;
        }
    }
}

// Fetch Parent Categories for Dropdown
$parents_sql = "SELECT * FROM TBL_MAIN_MENU WHERE STATUS = 'ACTIVE' ORDER BY SORT_ORDER ASC";
$parents = $db->query($parents_sql);
?>

<style>
    .toggle-btn-group .btn { border-color: var(--slcmc-orange); color: var(--slcmc-orange); }
    .toggle-btn-group .btn.active { background-color: var(--slcmc-orange); color: white; }
</style>

<section class="content-header">
    <div class="container-fluid">
        <h1 class="font-weight-bold text-primary"><i class="fas fa-plus-circle mr-2"></i>Register System Menu</h1>
    </div>
</section>

<section class="content">
    <div class="container-fluid">
        
        <!-- Global Same-Page Success Alert -->
        <?php if(!empty($current_status) && isset($system_messages[$current_status])): 
            $msg = $system_messages[$current_status];
        ?>
            <div class='alert alert-<?php echo $msg['type']; ?> shadow-sm border-0 alert-dismissible fade show mb-4'>
                <i class='fas <?php echo $msg['icon']; ?> mr-2'></i>
                <strong><?php echo $msg['title']; ?>:</strong> <?php echo $msg['msg']; ?>
                <button type='button' class='close' data-dismiss='alert'>&times;</button>
            </div>
        <?php endif; ?>

        <!-- Menu Type Toggle -->
        <div class="row justify-content-center mb-4">
            <div class="col-md-6 text-center">
                <div class="btn-group btn-group-toggle toggle-btn-group w-100 shadow-sm" data-toggle="buttons">
                    <label class="btn btn-outline-primary active py-2 font-weight-bold" onclick="toggleMenuType('child')">
                        <input type="radio" name="menu_type_selector" autocomplete="off" checked> 
                        <i class="fas fa-link mr-2"></i> ADD CHILD PAGE
                    </label>
                    <label class="btn btn-outline-primary py-2 font-weight-bold" onclick="toggleMenuType('parent')">
                        <input type="radio" name="menu_type_selector" autocomplete="off"> 
                        <i class="fas fa-folder mr-2"></i> ADD PARENT CATEGORY
                    </label>
                </div>
            </div>
        </div>

        <form action="" method="POST">
            <input type="hidden" name="menu_type" id="menu_type" value="child">

            <!-- CHILD PAGE FORM -->
            <div class="card card-outline card-primary shadow-sm" id="form_child">
                <div class="card-header bg-white">
                    <h3 class="card-title font-weight-bold text-primary">Child Page Details</h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 form-group">
                            <label class="text-secondary">Select Parent Category <span class="text-danger">*</span></label>
                            <select name="main_menu_id" id="main_menu_id" class="form-control req-child" required onchange="getNextOrder(this.value)">
                                <option value="">-- Select Parent --</option>
                                <?php while($p = mysqli_fetch_assoc($parents)): ?>
                                    <option value="<?php echo $p['MAIN_MENU_ID']; ?>"><?php echo $p['MENU_NAME']; ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="col-md-4 form-group">
                            <label class="text-secondary">Page Display Name <span class="text-danger">*</span></label>
                            <input type="text" name="child_name" class="form-control req-child" placeholder="e.g. Token Reception" required>
                        </div>
                        <div class="col-md-2 form-group">
                            <label class="text-secondary">Display Order</label>
                            <input type="number" name="child_order" id="child_order" class="form-control req-child" value="1" required>
                        </div>
                        <div class="col-md-2 form-group">
                            <label class="text-secondary">Status</label>
                            <select name="child_status" class="form-control">
                                <option value="ACTIVE">ACTIVE</option>
                                <option value="INACTIVE">INACTIVE</option>
                            </select>
                        </div>
                    </div>
                    
                    <hr>
                    
                    <div class="row bg-light p-3 rounded border">
                        <div class="col-md-6 form-group mb-0">
                            <label class="text-dark">Module Name (Folder) <span class="text-danger">*</span></label>
                            <input type="text" name="module_name" class="form-control req-child border-primary" placeholder="e.g. reception" required>
                            <small class="text-muted">Must match exact folder name in <code>modules/</code></small>
                        </div>
                        <div class="col-md-6 form-group mb-0">
                            <label class="text-dark">Page Action (File Prefix) <span class="text-danger">*</span></label>
                            <input type="text" name="page_name" class="form-control req-child border-primary" placeholder="e.g. list" required>
                            <small class="text-muted">Router will look for <code>list_reception.php</code></small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- PARENT CATEGORY FORM -->
            <div class="card card-outline card-primary shadow-sm" id="form_parent" style="display:none;">
                <div class="card-header bg-white">
                    <h3 class="card-title font-weight-bold text-primary">Parent Category Details</h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 form-group">
                            <label class="text-secondary">Category Name <span class="text-danger">*</span></label>
                            <input type="text" name="parent_name" class="form-control req-parent" placeholder="e.g. Operations">
                        </div>
                        <div class="col-md-4 form-group">
                            <label class="text-secondary">Icon (FontAwesome) <span class="text-danger">*</span></label>
                            <input type="text" name="parent_icon" class="form-control req-parent" placeholder="e.g. fas fa-truck">
                        </div>
                        <div class="col-md-2 form-group">
                            <label class="text-secondary">Display Order</label>
                            <input type="number" name="parent_order" class="form-control req-parent" value="1">
                        </div>
                        <div class="col-md-2 form-group">
                            <label class="text-secondary">Status</label>
                            <select name="parent_status" class="form-control">
                                <option value="ACTIVE">ACTIVE</option>
                                <option value="INACTIVE">INACTIVE</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Global Submit Button -->
            <div class="text-right mb-5">
                <a href="index.php?s=<?php echo encrypt_url('mod=menue&page=list_menu'); ?>" class="btn btn-default mr-2 px-4">View All Menus</a>
                <button type="submit" class="btn btn-primary px-5 font-weight-bold shadow-sm">
                    <i class="fas fa-save mr-2"></i> SAVE MENU
                </button>
            </div>
        </form>
    </div>
</section>

<script>
function toggleMenuType(type) {
    $('#menu_type').val(type);
    
    if(type === 'child') {
        $('#form_parent').hide();
        $('#form_child').fadeIn();
        
        $('.req-parent').prop('required', false);
        $('.req-child').prop('required', true);
    } else {
        $('#form_child').hide();
        $('#form_parent').fadeIn();
        
        $('.req-child').prop('required', false);
        $('.req-parent').prop('required', true);
    }
}

function getNextOrder(mid) {
    if(!mid) return;
    $.get('index.php?s=<?php echo encrypt_url("mod=menue&page=add_menue"); ?>&get_order=1&mid='+mid, function(data){
        var numbers = data.match(/\d+/g);
        if (numbers) {
            var finalOrder = numbers[numbers.length - 1];
            $('#child_order').val(finalOrder);
        }
    });
}
</script>