<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php init_head(); ?>
<div id="wrapper">
    <div class="content">
       <?php echo form_open(
    $edit_project
        ? admin_url('project_costing/project_costing/edit/' . $edit_project['id'])
        : admin_url('project_costing/project_costing/create'),
    ['id' => 'project-costing-form']
); ?>

     <div class="panel_s">
    <div class="panel-body">
        <div class="pc-form-header">
            <h4 class="no-margin">
                <?php echo isset($edit_project) && $edit_project ? 'Edit Project Costing' : 'New Project Costing'; ?>
            </h4>
            <p class="text-muted mtop5 mbot0">
                Complete the project details below, then add your costing items in each section.
            </p>
        </div>

        <hr class="hr-panel-heading" />

        <div class="pc-form-box">
            <div class="row" style="padding-bottom: 30px;">
                <div class="col-md-6">
                    <?php echo render_input('proposal_name', 'Proposal Name', $edit_project['proposal_name'] ?? ''); ?>
                </div>

                <div class="col-md-6">
                    <?php echo render_input('client_name', 'Client Name', $edit_project['client_name'] ?? ''); ?>
                </div>

               <div class="col-md-4">
    <label for="client_category_id" class="pc-step-label">
        <span class="pc-step-badge">1</span>
        Client Category
    </label>
    <select name="client_category_id" id="client_category_id" class="selectpicker" data-width="100%" data-live-search="true" required>
        <option value="">Select Client Category</option>
        <?php foreach ($client_categories as $category) { ?>
            <option value="<?php echo $category['id']; ?>" <?php echo isset($edit_project) && $edit_project && $edit_project['client_category_id'] == $category['id'] ? 'selected' : ''; ?>>
                <?php echo html_escape($category['name']); ?>
            </option>
        <?php } ?>
    </select>
</div>

<div class="col-md-4">
    <label for="engagement_type_id" class="pc-step-label">
        <span class="pc-step-badge">2</span>
        Type of Engagement
    </label>
    <select name="engagement_type_id" id="engagement_type_id" class="selectpicker" data-width="100%" data-live-search="true" required>
        <option value="">Select Type of Engagement</option>
    </select>
</div>

<div class="col-md-4">
    <label for="engagement_mode" class="pc-step-label">
        <span class="pc-step-badge">3</span>
        Engagement Mode
    </label>
    <select name="engagement_mode" id="engagement_mode" class="selectpicker" data-width="100%" required>
        <option value="">Select Mode</option>
        <option value="bidding" <?php echo isset($edit_project) && $edit_project && $edit_project['engagement_mode'] == 'bidding' ? 'selected' : ''; ?>>
            Bidding
        </option>
        <option value="non_bidding" <?php echo isset($edit_project) && $edit_project && $edit_project['engagement_mode'] == 'non_bidding' ? 'selected' : ''; ?>>
            Non Bidding
        </option>
    </select>
</div>
            </div>
        </div>
<div class="col-md-12">
    <small id="bidding-input-hint" class="text-warning" style="display:none;">
        For Bidding mode, please enter SME %, Admin % and Profit % manually.
    </small>
</div>
        <div class="pc-percentage-box mtop20">
            <div class="row">
   <div class="col-md-3 sst-field-wrap">
    <div class="form-group" app-field-wrapper="display_sst">
        <label for="display_sst" class="control-label">SST %</label>
        <select name="display_sst" id="display_sst" class="selectpicker form-control" data-width="100%" required>
            <option value="">Select SST %</option>
            <option value="0">0%</option>
            <option value="6">6%</option>
            <option value="8">8%</option>
        </select>
    </div>
    <div id="sst-validation-alert" class="mtop10"></div>
</div>

               <div class="col-md-3">
    <?php echo render_input(
        'display_sme',
        'SME %',
        '',
        'number',
        ['id' => 'display_sme', 'step' => '0.01', 'min' => '0', 'max' => '100']
    ); ?>
</div>
<div class="col-md-3">
    <?php echo render_input(
        'display_admin',
        'Admin %',
        '',
        'number',
        ['id' => 'display_admin', 'step' => '0.01', 'min' => '0', 'max' => '100']
    ); ?>
</div>
<div class="col-md-3">
    <?php echo render_input(
        'display_profit',
        'Profit %',
        '',
        'number',
        ['id' => 'display_profit', 'step' => '0.01', 'min' => '0', 'max' => '100']
    ); ?>
</div>
<div class="col-md-12">
    <div id="bidding-percentage-alert" class="mtop10"></div>
</div>

            </div>
        </div>
    </div>
</div>

        <div class="pc-section-box">
            <div class="pc-section-title">A. Subject Matter Expert (SME)</div>
            <div class="table-responsive">
                <table class="table table-bordered" id="programme-table">
                    <thead>
                        <tr>
                            <th>Item Name</th>
                            <th width="180">Type</th>
                            <th width="120">Frequency</th>
                            <th width="140">Rate</th>
                            <th width="140">Amount</th>
                            <th width="80">Action</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                    <tfoot>
                        <tr><td colspan="8"><span class="info-text" style="font-size: 13px;">
      <i class="fa fa-info-circle" style="color: blue;"></i><b> Frequency:</b> Frequency by No. of Session/Days/Months .
    </span><br></td></tr>
                        <tr>
                            <td colspan="6">
                                <button type="button" class="btn btn-success" id="add-programme-row">
                                    <i class="fa fa-plus"></i> Add Row
                                </button>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4" class="text-right"><strong>Total</strong></td>
                            <td colspan="2"><input type="text" id="programme_total_display" class="form-control" readonly></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
              <div id="programme-validation-alert" class="mtop10"></div>
        </div>

        <div class="pc-section-box">
            <div class="pc-section-title">B. Admin</div>
            <div class="table-responsive">
                <table class="table table-bordered" id="other-table">
                    <thead>
                        <tr>
                            <th>Item Name</th>
                           <th width="180">Type / Qualification</th>
                            <th width="120">Frequency</th>
                            <th width="140">Rate</th>
                            <th width="140">Amount</th>
                            <th width="80">Action</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                    <tfoot>
                        <tr><td colspan="8"><span class="info-text" style="font-size: 13px;">
      <i class="fa fa-info-circle" style="color: blue;"></i><b> Frequency:</b> Frequency by No. of Session/Days/Months .
    </span><br></td></tr>
                        <tr>
                            <td colspan="6">
                                <button type="button" class="btn btn-success" id="add-other-row">
                                    <i class="fa fa-plus"></i> Add Row
                                </button>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4" class="text-right"><strong>Total</strong></td>
                            <td colspan="2"><input type="text" id="other_total_display" class="form-control" readonly></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <div id="other-validation-alert" class="mtop10"></div>
        </div>

        <div class="pc-section-box">
            <div class="pc-section-title">C. Indirect Cost</div>
            <div class="table-responsive">
                <table class="table table-bordered" id="indirect-table">
                    <thead>
                        <tr>
                            <th>Item Name</th>
                            <th width="100">Qty</th>
                            <th width="140">Rate</th>
                            <th width="140">Amount</th>
                            <th width="80">Action</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                    <tfoot>
                        
                        <tr>
                            <td colspan="5">
                                <button type="button" class="btn btn-success" id="add-indirect-row">
                                    <i class="fa fa-plus"></i> Add Row
                                </button>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="3" class="text-right"><strong>Total</strong></td>
                            <td colspan="2"><input type="text" id="indirect_total_display" class="form-control" readonly></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
            <div id="indirect-validation-alert" class="mtop10"></div>
        </div>

        <div class="panel_s">
            <div class="panel-body">
                <div class="pc-summary-box">
                    <div class="row">
                        <div class="col-md-3">
                            <label>Programme Total</label>
                            <input type="text" id="summary_programme_total" class="form-control" readonly>
                        </div>
                        <div class="col-md-3">
                            <label>Other Related Total</label>
                            <input type="text" id="summary_other_total" class="form-control" readonly>
                        </div>
                        <div class="col-md-3">
                            <label>Indirect Total</label>
                            <input type="text" id="summary_indirect_total" class="form-control" readonly>
                        </div>
                        <div class="col-md-3">
                            <label>Overall Total</label>
                            <input type="text" id="summary_overall_total" class="form-control" readonly>
                        </div>
                        <input type="hidden" name="validation_warning_flag" id="validation_warning_flag" value="0">
                    </div>
                </div>

                <div class="mtop20">
                    <button type="submit" class="btn btn-primary">Submit Project Costing</button>
                    <a href="<?php echo admin_url('project_costing/project_costing'); ?>" class="btn btn-default">Cancel</a>
                </div>
            </div>
        </div>

        <?php echo form_close(); ?>
    </div>
</div>
<?php init_tail(); ?>
<script>
var editProject = <?php echo json_encode($edit_project ?? null); ?>;
var editItems = <?php echo json_encode($edit_items ?? ['programme'=>[], 'other_related'=>[], 'indirect'=>[]]); ?>;
var isEditMode = !!(editProject && editProject.id);
</script>
<script>
function formatMoney(num) {
    return parseFloat(num || 0).toFixed(2);
}

function getSelectedPercentages() {
    let type = $('#engagement_type_id').data('details');
    let mode = $('#engagement_mode').val();

    let percentages = {
        programme: 0,
        other: 0,
        profit: 0,
        sst: 0
    };

    if (!type || !mode) {
        return percentages;
    }

    //percentages.sst = parseFloat(type.sst_percent) || 0;
    percentages.sst = parseFloat($('#display_sst').val()) || 0;

    if (mode === 'bidding') {
        percentages.programme = parseFloat($('#display_sme').val()) || 0;
        percentages.other = parseFloat($('#display_admin').val()) || 0;
        percentages.profit = parseFloat($('#display_profit').val()) || 0;
    } else {
        percentages.programme = parseFloat(type.non_bidding_sme) || 0;
        percentages.other = parseFloat(type.non_bidding_admin) || 0;
        percentages.profit = parseFloat(type.non_bidding_profit) || 0;
    }

    return percentages;
}

function getSectionTotals() {
    return {
        programme: parseFloat($('#summary_programme_total').val()) || 0,
        other: parseFloat($('#summary_other_total').val()) || 0,
        indirect: parseFloat($('#summary_indirect_total').val()) || 0
    };
}

function calculateContractSummary() {
    let totals = getSectionTotals();
    let percentages = getSelectedPercentages();

    let A = totals.programme;
    let B = totals.other;
    let C = totals.indirect;

    let baseTotal = A + B + C;

    let programmePercent = percentages.programme || 0;
    let otherPercent = percentages.other || 0;
    let profitPercent = percentages.profit || 0;
    let sstPercent = percentages.sst || 0;

    let divisorPercent = programmePercent + otherPercent;

    let profitInceif = 0;
    if (baseTotal > 0 && divisorPercent > 0) {
        profitInceif = (baseTotal / (divisorPercent / 100)) * (profitPercent / 100);
    }

    let totalContractValue = baseTotal + profitInceif;
    let sstAmount = totalContractValue * (sstPercent / 100);
    let grandTotal = totalContractValue + sstAmount;

    return {
        A: A,
        B: B,
        C: C,
        baseTotal: baseTotal,
        profitInceif: profitInceif,
        totalContractValue: totalContractValue,
        sstPercent: sstPercent,
        sstAmount: sstAmount,
        grandTotal: grandTotal
    };
}

function recalcSummary() {
    let summary = calculateContractSummary();

    // base sections
    $('#summary_overall_total').val(formatMoney(summary.baseTotal));

    // optional extra summary fields if you add them
    $('#summary_profit_inceif').val(formatMoney(summary.profitInceif));
    $('#summary_contract_value').val(formatMoney(summary.totalContractValue));
    $('#summary_sst_amount').val(formatMoney(summary.sstAmount));
    $('#summary_grand_total').val(formatMoney(summary.grandTotal));

    runAllocationWarnings();
}
</script>
<script>



function calculateContractTotal() {
    let totals = getSectionTotals();
    return totals.programme + totals.other + totals.indirect;
}




function clearValidationAlerts() {
    $('#programme-validation-alert').html('');
    $('#other-validation-alert').html('');
    $('#indirect-validation-alert').html('');
    $('#sst-validation-alert').html('');
}
function runAllocationWarnings() {
    clearValidationAlerts();

    let percentages = getSelectedPercentages();
    let summary = calculateContractSummary();

    // warnings start only when B has value
    if (summary.B <= 0 || summary.totalContractValue <= 0) {
        $('#validation_warning_flag').val(0);
        return false;
    }

    let actualProgrammePct = (summary.A / summary.totalContractValue) * 100;
    let actualOtherPct = (summary.B / summary.totalContractValue) * 100;
    let actualIndirectPct = (summary.C / summary.totalContractValue) * 100;
    let actualSstPct = (summary.sstAmount / summary.totalContractValue) * 100;

    let maxProgrammeAllowed = summary.totalContractValue * (percentages.programme / 100);
    let maxOtherAllowed = summary.totalContractValue * (percentages.other / 100);
    let maxSstAllowed = summary.totalContractValue * (percentages.sst / 100);

    let hasWarning = false;

    if (summary.A > 0 && actualProgrammePct > percentages.programme) {
        hasWarning = true;
        $('#programme-validation-alert').html(`
            <div class="alert alert-warning">
                <strong>A.  Subject Matter Expert (SME)</strong> exceeds the allowed percentage of ${percentages.programme.toFixed(2)}%.
                <br>Current allocation: ${actualProgrammePct.toFixed(2)}%
                <br>Maximum allowed amount: RM ${formatMoney(maxProgrammeAllowed)}
                <br>Current amount: RM ${formatMoney(summary.A)}
            </div>
        `);
    }

    if (summary.B > 0 && actualOtherPct > percentages.other) {
        hasWarning = true;
        $('#other-validation-alert').html(`
            <div class="alert alert-warning">
                <strong>B. Other Related Cost</strong> exceeds the allowed percentage of ${percentages.other.toFixed(2)}%.
                <br>Current allocation: ${actualOtherPct.toFixed(2)}%
                <br>Maximum allowed amount: RM ${formatMoney(maxOtherAllowed)}
                <br>Current amount: RM ${formatMoney(summary.B)}
            </div>
        `);
    }

    // C validates against admin bucket
    if (summary.C > 0 && actualIndirectPct > percentages.other) {
        hasWarning = true;
        $('#indirect-validation-alert').html(`
            <div class="alert alert-warning">
                <strong>C. Indirect Cost</strong> exceeds the allowed Admin percentage of ${percentages.other.toFixed(2)}%.
                <br>Current allocation: ${actualIndirectPct.toFixed(2)}%
                <br>Maximum allowed amount: RM ${formatMoney(maxOtherAllowed)}
                <br>Current amount: RM ${formatMoney(summary.C)}
            </div>
        `);
    }

    // SST validation
    if (summary.sstAmount > 0 && actualSstPct > percentages.sst) {
        hasWarning = true;
        $('#sst-validation-alert').html(`
            <div class="alert alert-warning">
                <strong>SST</strong> exceeds the selected SST percentage of ${percentages.sst.toFixed(2)}%.
                <br>Current allocation: ${actualSstPct.toFixed(2)}%
                <br>Maximum allowed amount: RM ${formatMoney(maxSstAllowed)}
                <br>Current amount: RM ${formatMoney(summary.sstAmount)}
            </div>
        `);
    } else {
        $('#sst-validation-alert').html('');
    }

    $('#validation_warning_flag').val(hasWarning ? 1 : 0);
    return hasWarning;
}
function runAllocationWarnings__OLD() {
    clearValidationAlerts();

    let percentages = getSelectedPercentages();
    let summary = calculateContractSummary();

    // warnings start only when B has value
    if (summary.B <= 0 || summary.totalContractValue <= 0) {
        $('#validation_warning_flag').val(0);
        return false;
    }

    let actualProgrammePct = (summary.A / summary.totalContractValue) * 100;
    let actualOtherPct = (summary.B / summary.totalContractValue) * 100;
    let actualIndirectPct = (summary.C / summary.totalContractValue) * 100;

    let maxProgrammeAllowed = summary.totalContractValue * (percentages.programme / 100);
    let maxOtherAllowed = summary.totalContractValue * (percentages.other / 100);

    let hasWarning = false;

    if (summary.A > 0 && actualProgrammePct > percentages.programme) {
        hasWarning = true;
        $('#programme-validation-alert').html(`
            <div class="alert alert-warning">
                <strong>A. Programme Cost (F2F)</strong> exceeds the allowed percentage of ${percentages.programme.toFixed(2)}%.
                <br>Current allocation: ${actualProgrammePct.toFixed(2)}%
                <br>Maximum allowed amount: RM ${formatMoney(maxProgrammeAllowed)}
                <br>Current amount: RM ${formatMoney(summary.A)}
            </div>
        `);
    }

    if (summary.B > 0 && actualOtherPct > percentages.other) {
        hasWarning = true;
        $('#other-validation-alert').html(`
            <div class="alert alert-warning">
                <strong>B. Other Related Cost</strong> exceeds the allowed percentage of ${percentages.other.toFixed(2)}%.
                <br>Current allocation: ${actualOtherPct.toFixed(2)}%
                <br>Maximum allowed amount: RM ${formatMoney(maxOtherAllowed)}
                <br>Current amount: RM ${formatMoney(summary.B)}
            </div>
        `);
    }

    // You said C should also validate against admin bucket
    if (summary.C > 0 && actualIndirectPct > percentages.other) {
        hasWarning = true;
        $('#indirect-validation-alert').html(`
            <div class="alert alert-warning">
                <strong>C. Indirect Cost</strong> exceeds the allowed Admin percentage of ${percentages.other.toFixed(2)}%.
                <br>Current allocation: ${actualIndirectPct.toFixed(2)}%
                <br>Maximum allowed amount: RM ${formatMoney(maxOtherAllowed)}
                <br>Current amount: RM ${formatMoney(summary.C)}
            </div>
        `);
    }

    $('#validation_warning_flag').val(hasWarning ? 1 : 0);
    return hasWarning;
}




function calculateDepartmentTotal() {
    let programmeTotal = parseFloat($('#summary_programme_total').val()) || 0; // SME
    let otherRelatedTotal = parseFloat($('#summary_other_total').val()) || 0;  // Admin
    let indirectTotal = parseFloat($('#summary_indirect_total').val()) || 0;   // Profit/Other


    let percentages = getSelectedPercentages();

    let smePercent = percentages.sme || 0;
    let adminPercent = percentages.admin || 0;
    let profitPercent = percentages.profit || 0;

    let smeDecimal = smePercent / 100;
    let adminDecimal = adminPercent / 100;
    let profitDecimal = profitPercent / 100;

    let divisor = (smeDecimal + adminDecimal);

    if (divisor <= 0) {
        return 0;
    }

    // this follows your old formula exactly
    let derivedProfitTotal = ((programmeTotal + otherRelatedTotal) / divisor) * profitDecimal;

    let departmentTotal = programmeTotal + otherRelatedTotal + indirectTotal + derivedProfitTotal;

    return departmentTotal;
}




function validateAllocationRules(showAlerts = true) {
    clearValidationAlerts();

    let percentages = getSelectedPercentages();
    let summary = calculateContractSummary();

    // Validation starts only when B has value
    if (summary.B <= 0 || summary.contractTotal <= 0) {
        return true;
    }

    let actualProgrammePct = (summary.A / summary.contractTotal) * 100;
    let actualOtherPct = (summary.B / summary.contractTotal) * 100;
    let actualIndirectPct = (summary.indirect / summary.contractTotal) * 100;

    let maxProgrammeAllowed = summary.contractTotal * (percentages.programme / 100);
    let maxOtherAllowed = summary.contractTotal * (percentages.other / 100);
    let maxIndirectAllowed = summary.contractTotal * (percentages.indirect / 100);

    let isValid = true;

    if (summary.A > 0 && actualProgrammePct > percentages.programme) {
        isValid = false;
        if (showAlerts) {
            $('#programme-validation-alert').html(`
                <div class="alert alert-danger">
                    <strong>A. Programme Cost (F2F)</strong> exceeds the allowed percentage of ${percentages.programme.toFixed(2)}%.
                    <br>Current allocation: ${actualProgrammePct.toFixed(2)}%
                    <br>Maximum allowed amount: RM ${formatMoney(maxProgrammeAllowed)}
                    <br>Current amount: RM ${formatMoney(summary.A)}
                </div>
            `);
        }
    }

    if (summary.B > 0 && actualOtherPct > percentages.other) {
        isValid = false;
        if (showAlerts) {
            $('#other-validation-alert').html(`
                <div class="alert alert-danger">
                    <strong>B. Other Related Cost</strong> exceeds the allowed percentage of ${percentages.other.toFixed(2)}%.
                    <br>Current allocation: ${actualOtherPct.toFixed(2)}%
                    <br>Maximum allowed amount: RM ${formatMoney(maxOtherAllowed)}
                    <br>Current amount: RM ${formatMoney(summary.B)}
                </div>
            `);
        }
    }

    if (summary.indirect > 0 && actualIndirectPct > percentages.indirect) {
        isValid = false;
        if (showAlerts) {
            $('#indirect-validation-alert').html(`
                <div class="alert alert-danger">
                    <strong>C. Indirect Cost</strong> exceeds the allowed percentage of ${percentages.indirect.toFixed(2)}%.
                    <br>Current allocation: ${actualIndirectPct.toFixed(2)}%
                    <br>Maximum allowed amount: RM ${formatMoney(maxIndirectAllowed)}
                    <br>Current calculated amount: RM ${formatMoney(summary.indirect)}
                </div>
            `);
        }
    }

    return isValid;
}




function validateSectionPercentages(showAlerts = true) {
    clearValidationAlerts();

    let programmeTotal = parseFloat($('#summary_programme_total').val()) || 0;
    let otherTotal = parseFloat($('#summary_other_total').val()) || 0;
    let indirectTotal = parseFloat($('#summary_indirect_total').val()) || 0;
    let overallTotal = parseFloat($('#summary_overall_total').val()) || 0;

    let percentages = getSelectedPercentages();
    let smePercent = percentages.sme || 0;
    let adminPercent = percentages.admin || 0;
    let profitPercent = percentages.profit || 0;

    let isValid = true;

    if (overallTotal <= 0) {
        return true;
    }

    let maxProgrammeAllowed = overallTotal * (smePercent / 100);
    let maxOtherAllowed = overallTotal * (adminPercent / 100);
    let maxIndirectAllowed = overallTotal * (profitPercent / 100);

    let programmeActualPercent = overallTotal > 0 ? ((programmeTotal / overallTotal) * 100) : 0;
    let otherActualPercent = overallTotal > 0 ? ((otherTotal / overallTotal) * 100) : 0;
    let indirectActualPercent = overallTotal > 0 ? ((indirectTotal / overallTotal) * 100) : 0;

    if (programmeTotal > 0 && programmeTotal > maxProgrammeAllowed) {
        isValid = false;
        if (showAlerts) {
            $('#programme-validation-alert').html(`
                <div class="alert alert-danger">
                    <strong>Programme Cost validation:</strong><br>
                    Programme total exceeds the allowed SME percentage of ${smePercent.toFixed(2)}%.
                    <br>Current allocation: ${programmeActualPercent.toFixed(2)}%
                    <br>Maximum allowed: RM ${formatMoney(maxProgrammeAllowed)}
                    <br>Current total: RM ${formatMoney(programmeTotal)}
                </div>
            `);
        }
    }

    if (otherTotal > 0 && otherTotal > maxOtherAllowed) {
        isValid = false;
        if (showAlerts) {
            $('#other-validation-alert').html(`
                <div class="alert alert-danger">
                    <strong>Other Related Cost validation:</strong><br>
                    Other Related total exceeds the allowed Admin percentage of ${adminPercent.toFixed(2)}%.
                    <br>Current allocation: ${otherActualPercent.toFixed(2)}%
                    <br>Maximum allowed: RM ${formatMoney(maxOtherAllowed)}
                    <br>Current total: RM ${formatMoney(otherTotal)}
                </div>
            `);
        }
    }

    if (indirectTotal > 0 && indirectTotal > maxIndirectAllowed) {
        isValid = false;
        if (showAlerts) {
            $('#indirect-validation-alert').html(`
                <div class="alert alert-danger">
                    <strong>Indirect Cost validation:</strong><br>
                    Indirect total exceeds the allowed Profit percentage of ${profitPercent.toFixed(2)}%.
                    <br>Current allocation: ${indirectActualPercent.toFixed(2)}%
                    <br>Maximum allowed: RM ${formatMoney(maxIndirectAllowed)}
                    <br>Current total: RM ${formatMoney(indirectTotal)}
                </div>
            `);
        }
    }

    return isValid;
}
function toggleProgrammeJobGrade($row) {
    let type = $row.find('.programme-type').val();
    let $box = $row.find('.programme-job-grade-box');
    let $input = $row.find('.programme-job-grade');

    if (type === 'Internal') {
        $box.show();
        $input.prop('required', true);
    } else {
        $box.hide();
        $input.prop('required', false).val('');
    }
}
function addProgrammeRow(item = null) {
    item = item || {};

    let expertType = item.expert_type || '';
    let jobGrade = item.job_grade || '';
    let showJobGrade = expertType === 'Internal' ? '' : 'style="display:none;"';

    let row = `
        <tr class="programme-row">
            <td>
                <input type="text" name="programme_name[]" class="form-control" placeholder="Enter Item Name" value="${item.item_name || ''}">
                <textarea name="programme_remarks[]" class="form-control mtop5" placeholder="Remarks">${item.remarks || ''}</textarea>
            </td>

            <td>
                <select name="programme_type[]" class="form-control programme-type" required>
                    <option value="">Select Type</option>
                    <option value="Internal" ${expertType === 'Internal' ? 'selected' : ''}>Internal</option>
                    <option value="External" ${expertType === 'External' ? 'selected' : ''}>External</option>
                </select>

                <div class="programme-job-grade-box mtop5" ${showJobGrade}>
                    <input type="text" name="programme_job_grade[]" class="form-control programme-job-grade" placeholder="Enter Job Grade" value="${jobGrade}">
                </div>
            </td>

            <td>
                <input type="number" min="1" step="1.00" name="programme_frequency[]" class="form-control programme-frequency" value="${item.frequency || 1}">
            </td>

            <td>
                <input type="number" min="0" step="1.00" name="programme_rate[]" class="form-control programme-rate" value="${item.rate || 0}">
            </td>

            <td>
                <input type="text" class="form-control programme-amount" readonly value="${item.amount || '0.00'}">
            </td>

            <td>
                <button type="button" class="btn btn-danger remove-row"><i class="fa fa-remove"></i></button>
            </td>
        </tr>
    `;

    $('#programme-table tbody').append(row);

    let $newRow = $('#programme-table tbody tr.programme-row:last');
    toggleProgrammeJobGrade($newRow);
}
function toggleProgrammeJobGrade($row) {
    let type = $row.find('.programme-type').val();
    let $box = $row.find('.programme-job-grade-box');
    let $input = $row.find('.programme-job-grade');

    if (type === 'Internal') {
        $box.show();
        $input.prop('required', true);
    } else {
        $box.hide();
        $input.prop('required', false).val('');
    }
}
// function addProgrammeRow(item = null) {
//     item = item || {};

//     let expertType = item.expert_type || '';
//     let jobGrade = item.job_grade || '';
//     let showJobGrade = expertType === 'Internal' ? '' : 'style="display:none;"';

//     let row = `
//         <tr class="programme-row">
//             <td>
//                 <input type="text" name="programme_name[]" class="form-control" placeholder="Enter Item Name" value="${item.item_name || ''}">
//                 <textarea name="programme_remarks[]" class="form-control mtop5" placeholder="Remarks">${item.remarks || ''}</textarea>
//             </td>

//             <td>
//                 <select name="programme_type[]" class="form-control programme-type" required>
//                     <option value="">Select Type</option>
//                     <option value="Internal" ${expertType === 'Internal' ? 'selected' : ''}>Internal</option>
//                     <option value="External" ${expertType === 'External' ? 'selected' : ''}>External</option>
//                 </select>

//                 <div class="programme-job-grade-box mtop5" ${showJobGrade}>
//                     <input type="text" name="programme_job_grade[]" class="form-control programme-job-grade" placeholder="Enter Job Grade" value="${jobGrade}">
//                 </div>
//             </td>

//             <td>
//                 <input type="number" min="1" step="1.00" name="programme_frequency[]" class="form-control programme-frequency" value="${item.frequency || 1}">
//             </td>

//             <td>
//                 <input type="number" min="0" step="1.00" name="programme_rate[]" class="form-control programme-rate" value="${item.rate || 0}">
//             </td>

//             <td>
//                 <input type="text" class="form-control programme-amount" readonly value="${item.amount || '0.00'}">
//             </td>

//             <td>
//                 <button type="button" class="btn btn-danger remove-row"><i class="fa fa-remove"></i></button>
//             </td>
//         </tr>
//     `;

//     $('#programme-table tbody').append(row);

//     let $newRow = $('#programme-table tbody tr.programme-row:last');
//     toggleProgrammeJobGrade($newRow);
// }
// function addOtherRow(item = null) {
//     item = item || {};

//     const adminItems = [
//         'Report design (including design services, typesetting & infographic design)',
//         'Focus Group Discussion – venue rental, catering, token of appreciation',
//         'Editor',
//         'Proofreader/Reviewer',
//         'Other expenses (stamping/bank charges)',
//         'Tax – if requested by the client',
//         'Printing',
//         'Project Manager',
//         'Research Assistant',
//         'Enumerators',
//         'Training and Workshop',
//         'Software',
//         'Travel and accommodation',
//         'Publication',
//         'Others'
//     ];

//     const researchLevels = ['Degree', 'Master', 'PhD'];

//     let itemOptions = `<option value="">Select Item</option>`;
//     adminItems.forEach(function (val) {
//         itemOptions += `<option value="${val}" ${item.item_name === val ? 'selected' : ''}>${val}</option>`;
//     });

//     let qualificationOptions = `<option value="">Select Qualification</option>`;
//     researchLevels.forEach(function (val) {
//         qualificationOptions += `<option value="${val}" ${item.ra_level === val ? 'selected' : ''}>${val}</option>`;
//     });

//     let isRA = item.item_name === 'Research Assistant';

//     let row = `
//         <tr class="other-row">
//             <td>
//                 <select name="other_name[]" class="form-control other-item-name" required>
//                     ${itemOptions}
//                 </select>
//                 <textarea name="other_remarks[]" class="form-control mtop5" placeholder="Remarks">${item.remarks || ''}</textarea>
//             </td>

//             <td>
//                 <div class="other-qty-box" ${isRA ? 'style="display:none;"' : ''}>
//                     <input type="number" min="1" step="1.00" name="other_qty[]" class="form-control other-qty" value="${item.qty || 1}">
//                 </div>

//                 <div class="other-ra-box" ${isRA ? '' : 'style="display:none;"'}>
//                     <select name="other_ra_level[]" class="form-control other-ra-level">
//                         ${qualificationOptions}
//                     </select>
//                 </div>
//             </td>

//             <td>
//                 <input type="number" min="1" step="1.00" name="other_frequency[]" class="form-control other-frequency" value="${item.frequency || 1}">
//             </td>

//             <td>
//                 <input type="number" min="0" step="1.00" name="other_rate[]" class="form-control other-rate" value="${item.rate || 0}" ${isRA ? 'readonly' : ''}>
//             </td>

//             <td>
//                 <input type="text" class="form-control other-amount" readonly value="${item.amount || '0.00'}">
//             </td>

//             <td>
//                 <button type="button" class="btn btn-danger remove-row"><i class="fa fa-remove"></i></button>
//             </td>
//         </tr>
//     `;

//     $('#other-table tbody').append(row);

//     let $newRow = $('#other-table tbody tr.other-row:last');
//     toggleResearchAssistantMode($newRow);
// }
function addOtherRow(item = null) {
    item = item || {};

    const adminItems = [
        'Report design (including design services, typesetting & infographic design)',
        'Focus Group Discussion – venue rental, catering, token of appreciation',
        'Editor',
        'Proofreader/Reviewer',
        'Other expenses (stamping/bank charges)',
        'Tax – if requested by the client',
        'Printing',
        'Project Manager',
        'Research Assistant',
        'Enumerators',
        'Training and Workshop',
        'Software',
        'Travel and accommodation',
        'Publication',
        'Others'
    ];

    const researchLevels = ['Degree', 'Master', 'PhD'];

    let itemOptions = `<option value="">Select Item</option>`;
    adminItems.forEach(function (val) {
        itemOptions += `<option value="${val}" ${item.item_name === val ? 'selected' : ''}>${val}</option>`;
    });

    let qualificationOptions = `<option value="">Select Qualification</option>`;
    researchLevels.forEach(function (val) {
        qualificationOptions += `<option value="${val}" ${item.ra_level === val ? 'selected' : ''}>${val}</option>`;
    });

    let isRA = item.item_name === 'Research Assistant';

    let row = `
        <tr class="other-row">
            <td>
                <select name="other_name[]" class="form-control other-item-name" required>
                    ${itemOptions}
                </select>
                <textarea name="other_remarks[]" class="form-control mtop5" placeholder="Remarks">${item.remarks || ''}</textarea>
            </td>

            <td>
                <div class="other-qty-box" ${isRA ? 'style="display:none;"' : ''}>
                    <input type="number" min="1" step="1.00" name="other_qty[]" class="form-control other-qty" value="${item.qty || 1}">
                </div>

                <div class="other-ra-box" ${isRA ? '' : 'style="display:none;"'}>
                    <select name="other_ra_level[]" class="form-control other-ra-level">
                        ${qualificationOptions}
                    </select>
                </div>
            </td>

            <td>
                <input type="number" min="1" step="1.00" name="other_frequency[]" class="form-control other-frequency" value="${item.frequency || 1}">
            </td>

            <td>
                <input type="number" min="0" step="1.00" name="other_rate[]" class="form-control other-rate" value="${item.rate || 0}" ${isRA ? 'readonly' : ''}>
            </td>

            <td>
                <input type="text" class="form-control other-amount" readonly value="${item.amount || '0.00'}">
            </td>

            <td>
                <button type="button" class="btn btn-danger remove-row"><i class="fa fa-remove"></i></button>
            </td>
        </tr>
    `;

    $('#other-table tbody').append(row);

    let $newRow = $('#other-table tbody tr.other-row:last');
    toggleResearchAssistantMode($newRow);
}
function toggleResearchAssistantMode($row) {
    let itemName = $row.find('.other-item-name').val();
    let $qtyBox = $row.find('.other-qty-box');
    let $qty = $row.find('.other-qty');
    let $raBox = $row.find('.other-ra-box');
    let $raLevel = $row.find('.other-ra-level');
    let $rate = $row.find('.other-rate');

    if (itemName === 'Research Assistant') {
        $qtyBox.hide();
        $qty.prop('required', false).val(1);

        $raBox.show();
        $raLevel.prop('required', true);

        let level = $raLevel.val();
        if (level === 'Degree') {
            $rate.val(1500);
        } else if (level === 'Master') {
            $rate.val(2000);
        } else if (level === 'PhD') {
            $rate.val(2500);
        } else {
            $rate.val(0);
        }

        $rate.prop('readonly', true);
    } else {
        $qtyBox.show();
        $qty.prop('required', true);

        $raBox.hide();
        $raLevel.prop('required', false).val('');

        $rate.prop('readonly', false);
    }

    recalcOther();
}

// function addProgrammeRow(item = null) {
//     item = item || {};
//     let row = `
//         <tr class="programme-row">
//             <td>
//                 <input type="text" name="programme_name[]" class="form-control" placeholder="Enter Item Name" value="${item.item_name || ''}">
//                 <textarea name="programme_remarks[]" class="form-control mtop5" placeholder="Remarks">${item.remarks || ''}</textarea>
//             </td>
//             <td><input type="number" min="1" step="1.00" name="programme_qty[]" class="form-control programme-qty" value="${item.qty || 1}"></td>
//             <td><input type="number" min="1" step="1.00" name="programme_frequency[]" class="form-control programme-frequency" value="${item.frequency || 1}"></td>
//             <td><input type="number" min="0" step="1.00" name="programme_rate[]" class="form-control programme-rate" value="${item.rate || 0}"></td>
//             <td><input type="text" class="form-control programme-amount" readonly value="${item.amount || '0.00'}"></td>
//             <td><button type="button" class="btn btn-danger remove-row"><i class="fa fa-remove"></i></button></td>
//         </tr>
//     `;
//     $('#programme-table tbody').append(row);
// }

// function addOtherRow(item = null) {
//     item = item || {};
//     let row = `
//         <tr class="other-row">
//             <td>
//                 <input type="text" name="other_name[]" class="form-control" placeholder="Enter Item Name" value="${item.item_name || ''}">
//                 <textarea name="other_remarks[]" class="form-control mtop5" placeholder="Remarks">${item.remarks || ''}</textarea>
//             </td>
//             <td><input type="number" min="1" step="1.00" name="other_qty[]" class="form-control other-qty" value="${item.qty || 1}"></td>
//             <td><input type="number" min="1" step="1.00" name="other_frequency[]" class="form-control other-frequency" value="${item.frequency || 1}"></td>
//             <td><input type="number" min="0" step="1.00" name="other_rate[]" class="form-control other-rate" value="${item.rate || 0}"></td>
//             <td><input type="text" class="form-control other-amount" readonly value="${item.amount || '0.00'}"></td>
//             <td><button type="button" class="btn btn-danger remove-row"><i class="fa fa-remove"></i></button></td>
//         </tr>
//     `;
//     $('#other-table tbody').append(row);
// }

function addIndirectRow(item = null) {
    item = item || {};
    let row = `
        <tr class="indirect-row">
            <td>
                <input type="text" name="indirect_name[]" class="form-control" placeholder="Enter Item Name" value="${item.item_name || ''}">
                <textarea name="indirect_remarks[]" class="form-control mtop5" placeholder="Remarks">${item.remarks || ''}</textarea>
            </td>
            <td><input type="number" min="1" step="1.00" name="indirect_qty[]" class="form-control indirect-qty" value="${item.qty || 1}"></td>
            <td><input type="number" min="0" step="1.00" name="indirect_rate[]" class="form-control indirect-rate" value="${item.rate || 0}"></td>
            <td><input type="text" class="form-control indirect-amount" readonly value="${item.amount || '0.00'}"></td>
            <td><button type="button" class="btn btn-danger remove-row"><i class="fa fa-remove"></i></button></td>
        </tr>
    `;
    $('#indirect-table tbody').append(row);
}

function recalcProgramme() {
    let total = 0;
    $('#programme-table tbody tr').each(function () {
        let qty = parseFloat($(this).find('.programme-qty').val()) || 0;
        let frequency = parseFloat($(this).find('.programme-frequency').val()) || 0;
        let rate = parseFloat($(this).find('.programme-rate').val()) || 0;
        let amount = qty * frequency * rate;
        $(this).find('.programme-amount').val(formatMoney(amount));
        total += amount;
    });

    $('#programme_total_display').val(formatMoney(total));
    $('#summary_programme_total').val(formatMoney(total));
    recalcSummary();
}
function recalcOther() {
    let total = 0;

    $('#other-table tbody tr').each(function () {
        let qty = parseFloat($(this).find('.other-qty').val()) || 0;
        let frequency = parseFloat($(this).find('.other-frequency').val()) || 0;
        let rate = parseFloat($(this).find('.other-rate').val()) || 0;

        let itemName = $(this).find('.other-item-name').val();
        if (itemName === 'Research Assistant') {
            qty = 1;
        }

        let amount = qty * frequency * rate;
        $(this).find('.other-amount').val(formatMoney(amount));
        total += amount;
    });

    $('#other_total_display').val(formatMoney(total));
    $('#summary_other_total').val(formatMoney(total));
    recalcSummary();
}
// function recalcOther() {
//     let total = 0;
//     $('#other-table tbody tr').each(function () {
//         let qty = parseFloat($(this).find('.other-qty').val()) || 0;
//         let frequency = parseFloat($(this).find('.other-frequency').val()) || 0;
//         let rate = parseFloat($(this).find('.other-rate').val()) || 0;
//         let amount = qty * frequency * rate;
//         $(this).find('.other-amount').val(formatMoney(amount));
//         total += amount;
//     });

//     $('#other_total_display').val(formatMoney(total));
//     $('#summary_other_total').val(formatMoney(total));
//     recalcSummary();
// }

function recalcIndirect() {
    let total = 0;
    $('#indirect-table tbody tr').each(function () {
        let qty = parseFloat($(this).find('.indirect-qty').val()) || 0;
        let rate = parseFloat($(this).find('.indirect-rate').val()) || 0;
        let amount = qty * rate;
        $(this).find('.indirect-amount').val(formatMoney(amount));
        total += amount;
    });

    $('#indirect_total_display').val(formatMoney(total));
    $('#summary_indirect_total').val(formatMoney(total));
    recalcSummary();
}

function loadEngagementTypes(categoryId, selectedId = '') {
    $('#engagement_type_id').html('<option value="">Loading...</option>');
    $('#engagement_type_id').selectpicker('refresh');

    $.post(admin_url + 'project_costing/project_costing/get_engagement_types_by_category', {
        client_category_id: categoryId
    }, function(response) {
        let types = JSON.parse(response);
        let html = '<option value="">Select Type of Engagement</option>';

        $.each(types, function(i, type) {
            let selected = (selectedId && selectedId == type.id) ? 'selected' : '';
            html += '<option value="' + type.id + '" ' + selected + '>' + type.name + '</option>';
        });

        $('#engagement_type_id').html(html);
        $('#engagement_type_id').selectpicker('refresh');

        if (selectedId) {
            loadEngagementDetails(selectedId);
        }
    });
}
function loadEngagementDetails(engagementTypeId) {
    $.post(admin_url + 'project_costing/project_costing/get_engagement_type_details', {
        engagement_type_id: engagementTypeId
    }, function(response) {
        let type = JSON.parse(response);

        //$('#display_sst').val(type.sst_percent);
        $('#display_sst').val(type.sst_percent).selectpicker('refresh');
        $('#engagement_type_id').data('details', type);

        updateDisplayedPercentages(type);
        runAllocationWarnings();
    });
}
function validateSstSelection() {
    let sst = $('#display_sst').val();

    if (sst === '' || sst === null) {
        $('#sst-validation-alert').html(`
            <div class="alert alert-warning">
                Please select SST %.
            </div>
        `);
        return false;
    }

    $('#sst-validation-alert').html('');
    return true;
}
function updateDisplayedPercentages(type) {
    let mode = $('#engagement_mode').val();

    if (!type || !mode) {
        $('#display_sme').val('').removeClass('pc-manual-input');
        $('#display_admin').val('').removeClass('pc-manual-input');
        $('#display_profit').val('').removeClass('pc-manual-input');

        $('#display_sst')
            .val('')
            .removeClass('pc-manual-input')
            .selectpicker('refresh');

        $('#display_sst').closest('.form-group').find('.bootstrap-select .dropdown-toggle')
            .removeClass('pc-manual-input');

        return;
    }

    if (mode === 'bidding') {
        let smeVal = '';
        let adminVal = '';
        let profitVal = '';
        let sstVal = '';

        // In edit mode, use saved project percentages
        if (isEditMode) {
            smeVal = editProject.bidding_sme_percent ?? '';
            adminVal = editProject.bidding_admin_percent ?? '';
            profitVal = editProject.bidding_profit_percent ?? '';
            sstVal = editProject.sst_percent ?? '';
        }

        $('#display_sme')
            .val(smeVal)
            .prop('readonly', false)
            .attr('placeholder', 'Enter SME %')
            .addClass('pc-manual-input');

        $('#display_admin')
            .val(adminVal)
            .prop('readonly', false)
            .attr('placeholder', 'Enter Admin %')
            .addClass('pc-manual-input');

        $('#display_profit')
            .val(profitVal)
            .prop('readonly', false)
            .attr('placeholder', 'Enter Profit %')
            .addClass('pc-manual-input');

        $('#display_sst')
            .val(sstVal)
            .addClass('pc-manual-input')
            .selectpicker('refresh');

        $('#display_sst').closest('.form-group').find('.bootstrap-select .dropdown-toggle')
            .addClass('pc-manual-input');

        // Focus SST first for bidding
        if (!isEditMode) {
            setTimeout(function () {
                $('#display_sst').closest('.form-group').find('.bootstrap-select .dropdown-toggle').focus();
            }, 100);
        }
    } else {
        $('#display_sme')
            .val(type.non_bidding_sme)
            .prop('readonly', true)
            .attr('placeholder', '')
            .removeClass('pc-manual-input');

        $('#display_admin')
            .val(type.non_bidding_admin)
            .prop('readonly', true)
            .attr('placeholder', '')
            .removeClass('pc-manual-input');

        $('#display_profit')
            .val(type.non_bidding_profit)
            .prop('readonly', true)
            .attr('placeholder', '')
            .removeClass('pc-manual-input');

        // SST stays manual even for non-bidding
      if (isEditMode) {
    $('#display_sst').val(editProject.sst_percent ?? '');
} else {
    $('#display_sst').val('');
}

$('#display_sst')
    .addClass('pc-manual-input')
    .selectpicker('refresh');

// add class AFTER refresh
setTimeout(function () {
    $('#display_sst')
        .closest('.form-group')
        .find('.bootstrap-select .dropdown-toggle')
        .addClass('pc-manual-input');
}, 0);

// Focus SME for non-bidding
setTimeout(function () {
    $('#display_sme').focus();
}, 100);

      
    }

    validateBiddingPercentages(true);
}
function updateDisplayedPercentages__OLD(type) {
    let mode = $('#engagement_mode').val();

    if (!type || !mode) {
        $('#display_sme').val('').removeClass('pc-manual-input');
        $('#display_admin').val('').removeClass('pc-manual-input');
        $('#display_profit').val('').removeClass('pc-manual-input');
        return;
    }

    if (mode === 'bidding') {
        let smeVal = '';
        let adminVal = '';
        let profitVal = '';

        // In edit mode, use the saved project percentages
        if (isEditMode) {
            smeVal = editProject.bidding_sme_percent ?? '';
            adminVal = editProject.bidding_admin_percent ?? '';
            profitVal = editProject.bidding_profit_percent ?? '';
        }

        $('#display_sme')
            .val(smeVal)
            .prop('readonly', false)
            .attr('placeholder', 'Enter SME %')
            .addClass('pc-manual-input');

        $('#display_admin')
            .val(adminVal)
            .prop('readonly', false)
            .attr('placeholder', 'Enter Admin %')
            .addClass('pc-manual-input');

        $('#display_profit')
            .val(profitVal)
            .prop('readonly', false)
            .attr('placeholder', 'Enter Profit %')
            .addClass('pc-manual-input');

        // Only focus for new create page, not edit page
        if (!isEditMode) {
            setTimeout(function () {
                $('#display_sme').focus();
            }, 100);
        }
    } else {
        $('#display_sme')
            .val(type.non_bidding_sme)
            .prop('readonly', true)
            .attr('placeholder', '')
            .removeClass('pc-manual-input');

        $('#display_admin')
            .val(type.non_bidding_admin)
            .prop('readonly', true)
            .attr('placeholder', '')
            .removeClass('pc-manual-input');

        $('#display_profit')
            .val(type.non_bidding_profit)
            .prop('readonly', true)
            .attr('placeholder', '')
            .removeClass('pc-manual-input');
    }

    validateBiddingPercentages(true);
}
$(function () {
    if (editProject && editItems) {
        if (editItems.programme && editItems.programme.length) {
            $.each(editItems.programme, function(i, item) {
                addProgrammeRow(item);
            });
        } else {
            addProgrammeRow();
        }

        if (editItems.other_related && editItems.other_related.length) {
            $.each(editItems.other_related, function(i, item) {
                addOtherRow(item);
            });
        } else {
            addOtherRow();
        }

        if (editItems.indirect && editItems.indirect.length) {
            $.each(editItems.indirect, function(i, item) {
                addIndirectRow(item);
            });
        } else {
            addIndirectRow();
        }

        if (editProject.client_category_id) {
            loadEngagementTypes(editProject.client_category_id, editProject.engagement_type_id);
        }
    } else {
        addProgrammeRow();
        addOtherRow();
        addIndirectRow();
    }

    $('#add-programme-row').on('click', function () {
        addProgrammeRow();
    });

    $('#add-other-row').on('click', function () {
        addOtherRow();
    });

    $('#add-indirect-row').on('click', function () {
        addIndirectRow();
    });

    $(document).on('click', '.remove-row', function () {
        $(this).closest('tr').remove();
        recalcProgramme();
        recalcOther();
        recalcIndirect();
    });

    $(document).on('input', '.programme-qty, .programme-frequency, .programme-rate', recalcProgramme);
    $(document).on('input', '.other-qty, .other-frequency, .other-rate', recalcOther);
    $(document).on('input', '.indirect-qty, .indirect-rate', recalcIndirect);

    $(document).on('input', '#display_sme, #display_admin, #display_profit', function () {
        validateBiddingPercentages(true);
        recalcSummary();
    });

    $('#client_category_id').on('changed.bs.select', function () {
        let categoryId = $(this).val();

        $('#display_sst').val('');
        $('#engagement_type_id').data('details', null);

        if (!isEditMode) {
            $('#display_sme').val('');
            $('#display_admin').val('');
            $('#display_profit').val('');
        }

        $('#bidding-percentage-alert').html('');
        clearValidationAlerts();

        if (categoryId) {
            loadEngagementTypes(categoryId);
        } else {
            $('#engagement_type_id').html('<option value="">Select Type of Engagement</option>');
            $('#engagement_type_id').selectpicker('refresh');
        }
    });

    $('#engagement_type_id').on('changed.bs.select', function () {
        let engagementTypeId = $(this).val();

        if (engagementTypeId) {
            loadEngagementDetails(engagementTypeId);
        } else {
            $('#engagement_type_id').data('details', null);
            clearValidationAlerts();
        }
    });

    $('#engagement_mode').on('changed.bs.select', function () {
        let type = $('#engagement_type_id').data('details');
        updateDisplayedPercentages(type);
        runAllocationWarnings();
    });

    recalcProgramme();
    recalcOther();
    recalcIndirect();

    $('#project-costing-form').on('submit', function (e) {
        recalcProgramme();
        recalcOther();
        recalcIndirect();

        runAllocationWarnings();

        let biddingValid = validateBiddingPercentages(true);
         let sstValid = validateSstSelection();

        if (!biddingValid || !sstValid) {
            alert('Please fix the Bidding percentages before submitting.');
            e.preventDefault();
            return false;
        }

        return true;
    });
});


//New Changes
function setPercentageFieldMode() {
    let mode = $('#engagement_mode').val();

    if (mode === 'bidding') {
        $('#display_sme').prop('readonly', false);
        $('#display_admin').prop('readonly', false);
        $('#display_profit').prop('readonly', false);
    } else {
        $('#display_sme').prop('readonly', true);
        $('#display_admin').prop('readonly', true);
        $('#display_profit').prop('readonly', true);
    }
}
function validateBiddingPercentages(showAlert = true) {
    let mode = $('#engagement_mode').val();
    $('#bidding-percentage-alert').html('');

    let sme = parseFloat($('#display_sme').val()) || 0;
    let admin = parseFloat($('#display_admin').val()) || 0;
    let profit = parseFloat($('#display_profit').val()) || 0;
    let sst = $('#display_sst').val();

    let errors = [];

    if (mode === 'bidding') {
        let total = sme + admin + profit;

        if (Math.abs(total - 100) > 0.01) {
            errors.push('Total of SME %, Admin % and Profit % must be 100%. Current total is ' + total.toFixed(2) + '%.');
        }

        if (sme > profit) {
            errors.push('SME % cannot be more than Profit %.');
        }
    }

    if (sst === '' || sst === null || typeof sst === 'undefined') {
        errors.push('Please select an appropriate SST% for this project.');
    }

    if (showAlert && errors.length > 0) {
        let html = '<div class="alert alert-warning">';
        html += '<strong>Project Validation</strong><br>';
        html += errors.join('<br>');
        html += '</div>';
        $('#bidding-percentage-alert').html(html);
    }

    return errors.length === 0;
}
function validateBiddingPercentages__OLD(showAlert = true) {
    let mode = $('#engagement_mode').val();
    $('#bidding-percentage-alert').html('');

    if (mode !== 'bidding') {
        return true;
    }

    let sme = parseFloat($('#display_sme').val()) || 0;
    let admin = parseFloat($('#display_admin').val()) || 0;
    let profit = parseFloat($('#display_profit').val()) || 0;

    let total = sme + admin + profit;
    let errors = [];

    if (Math.abs(total - 100) > 0.01) {
        errors.push('Total of SME %, Admin % and Profit % must be 100%. Current total is ' + total.toFixed(2) + '%.');
    }

   if (sme > profit) {
    errors.push('SME % cannot be more than Profit %.');
}

    if (showAlert && errors.length > 0) {
        let html = '<div class="alert alert-warning">';
        html += '<strong>Bidding Percentage Validation</strong><br>';
        html += errors.join('<br>');
        html += '</div>';
        $('#bidding-percentage-alert').html(html);
    }

    return errors.length === 0;
}
$(document).on('input', '#display_sme, #display_admin, #display_profit', function () {
    validateBiddingPercentages(true);
    recalcSummary();
});
$(document).on('change', '.programme-type', function () {
    let $row = $(this).closest('tr');
    toggleProgrammeJobGrade($row);
});
$(document).on('change', '.other-item-name', function () {
    let $row = $(this).closest('tr');
    toggleResearchAssistantMode($row);
});

$(document).on('change', '.other-ra-level', function () {
    let $row = $(this).closest('tr');
    toggleResearchAssistantMode($row);
});
$(document).on('change', '.programme-type', function () {
    let $row = $(this).closest('tr');
    toggleProgrammeJobGrade($row);
});
</script>