<?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="pc-percentage-box mtop20">
            <div class="row">
                <div class="col-md-3">
                    <?php echo render_input('display_sst', 'SST %', '', 'text', ['readonly' => true, 'id' => 'display_sst']); ?>
                </div>
                <div class="col-md-3">
                    <?php echo render_input('display_sme', 'SME %', '', 'text', ['readonly' => true, 'id' => 'display_sme']); ?>
                </div>
                <div class="col-md-3">
                    <?php echo render_input('display_admin', 'Admin %', '', 'text', ['readonly' => true, 'id' => 'display_admin']); ?>
                </div>
                <div class="col-md-3">
                    <?php echo render_input('display_profit', 'Profit %', '', 'text', ['readonly' => true, 'id' => 'display_profit']); ?>
                </div>
            </div>
        </div>
    </div>
</div>

        <div class="pc-section-box">
            <div class="pc-section-title">A. Programme Cost (F2F)</div>
            <div class="table-responsive">
                <table class="table table-bordered" id="programme-table">
                    <thead>
                        <tr>
                            <th>Item Name</th>
                            <th width="100">Qty</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. Other Related Cost (Additional Cost for F2F session)</div>
            <div class="table-responsive">
                <table class="table table-bordered" id="other-table">
                    <thead>
                        <tr>
                            <th>Item Name</th>
                            <th width="100">Qty</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'=>[]]); ?>;
</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;

    if (mode === 'bidding') {
        percentages.programme = parseFloat(type.bidding_sme) || 0;
        percentages.other = parseFloat(type.bidding_admin) || 0;
        percentages.profit = parseFloat(type.bidding_profit) || 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('');
}

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 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 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 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);
        $('#engagement_type_id').data('details', type);
        updateDisplayedPercentages(type);
        validateSectionPercentages(true);
    });
}

function updateDisplayedPercentages(type) {
    let mode = $('#engagement_mode').val();

    if (!type || !mode) {
        $('#display_sme').val('');
        $('#display_admin').val('');
        $('#display_profit').val('');
        return;
    }

    if (mode === 'bidding') {
        $('#display_sme').val(type.bidding_sme + '%');
        $('#display_admin').val(type.bidding_admin + '%');
        $('#display_profit').val(type.bidding_profit + '%');
    } else {
        $('#display_sme').val(type.non_bidding_sme + '%');
        $('#display_admin').val(type.non_bidding_admin + '%');
        $('#display_profit').val(type.non_bidding_profit + '%');
    }
}

$(function () {
    // preload edit rows or default empty rows
    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();
        }
    } 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);

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

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

        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(true);
    });

    // preload selected engagement type in edit mode
if (editProject && editProject.client_category_id) {
    loadEngagementTypes(editProject.client_category_id, editProject.engagement_type_id);
}
    recalcProgramme();
    recalcOther();
    recalcIndirect();

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

    runAllocationWarnings();

    // allow submit even if warnings exist
    return true;
});
});
</script>