<?php require_once __DIR__ . '/../includes/auth.php'; require_login(); ?>
<div class="page-salary_management">
  <div class="container-fluid p-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h4>Salary Management</h4>
      <div>
        <button id="btnAddEmployee" class="btn btn-primary me-2"><i class="bi bi-person-plus"></i> Add Employee</button>
      </div>
    </div>

  <!-- Allowance Modal -->
  <div class="modal fade" id="allModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header"><h5 class="modal-title">Add Allowance</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <form id="allForm">
          <div class="modal-body">
            <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
            <input type="hidden" name="id" id="allId">
            <div class="mb-2">
              <label class="form-label">Employee</label>
              <select class="form-select" name="employee_id" id="all_emp" required></select>
            </div>
            <div class="mb-2">
              <label class="form-label">Date</label>
              <input type="date" class="form-control" name="all_date" id="all_date" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Amount</label>
              <input type="number" step="0.01" class="form-control" name="amount" id="all_amount" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Reason</label>
              <input type="text" class="form-control" name="reason" id="all_reason">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Save</button>
          </div>
        </form>
      </div>
    </div>
  </div>
  <!-- Incentive Modal -->
  <div class="modal fade" id="incModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header"><h5 class="modal-title">Add OT</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <form id="incForm">
          <div class="modal-body">
            <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
            <input type="hidden" name="id" id="incId">
            <div class="mb-2">
              <label class="form-label">Employee</label>
              <select class="form-select" name="employee_id" id="inc_emp" required></select>
            </div>
            <div class="mb-2">
              <label class="form-label">Date</label>
              <input type="date" class="form-control" name="inc_date" id="inc_date" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Amount</label>
              <input type="number" step="0.01" class="form-control" name="amount" id="inc_amount" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Reason</label>
              <input type="text" class="form-control" name="reason" id="inc_reason">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Save</button>
          </div>
        </form>
      </div>
    </div>
  </div>
    <div class="row g-3">
      <div class="col-lg-6">
        <div class="card shadow-sm">
          <div class="card-header d-flex justify-content-between align-items-center">
            <strong>Employees</strong>
            <div class="d-flex align-items-center gap-2">
              <label class="small text-muted mb-0">Branch</label>
              <select id="empBranchFilter" class="form-select form-select-sm" style="min-width:200px"></select>
            </div>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-hover align-middle" id="emp-table">
                <thead><tr><th>Code</th><th>Name</th><th>Phone</th><th>Branch</th><th>Designation</th><th>Base Salary</th><th>Active</th><th>Actions</th></tr></thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>

      <div class="col-lg-6">
        <div class="card shadow-sm mb-3">
          <div class="card-header d-flex justify-content-between align-items-center">
            <strong>Salary Advances</strong>
            <button id="btnAddAdvanceCard" class="btn btn-sm btn-outline-primary"><i class="bi bi-cash-coin"></i> Add Advance</button>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-sm align-middle" id="adv-table">
                <thead><tr><th>Date</th><th>Employee</th><th>Amount</th><th>Notes</th><th>Actions</th></tr></thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>

        <div class="card shadow-sm">
          <div class="card-header d-flex justify-content-between align-items-center">
            <strong>Salary Deductions</strong>
            <button id="btnAddDeductionCard" class="btn btn-sm btn-outline-primary"><i class="bi bi-dash-circle"></i> Add Deduction</button>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-sm align-middle" id="ded-table">
                <thead><tr><th>Date</th><th>Employee</th><th>Amount</th><th>Reason</th><th>Actions</th></tr></thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>

        <div class="card shadow-sm mt-3">
          <div class="card-header d-flex justify-content-between align-items-center">
            <strong>OT</strong>
            <button id="btnAddIncentive" class="btn btn-sm btn-outline-primary"><i class="bi bi-gift"></i> Add OT</button>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-sm align-middle" id="inc-table">
                <thead><tr><th>Date</th><th>Employee</th><th>Amount</th><th>Reason</th><th>Actions</th></tr></thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>

        <div class="card shadow-sm mt-3">
          <div class="card-header d-flex justify-content-between align-items-center">
            <strong>Allowances</strong>
            <button id="btnAddAllowance" class="btn btn-sm btn-outline-primary"><i class="bi bi-wallet2"></i> Add Allowance</button>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-sm align-middle" id="all-table">
                <thead><tr><th>Date</th><th>Employee</th><th>Amount</th><th>Reason</th><th>Actions</th></tr></thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>

        <div class="card shadow-sm mt-3">
          <div class="card-header d-flex justify-content-between align-items-center">
            <strong>Payroll</strong>
            <div class="d-flex align-items-center gap-2">
              <select id="pay_month" class="form-select form-select-sm" style="width:auto">
                <?php for($m=1;$m<=12;$m++): $label=date('M', mktime(0,0,0,$m,10)); ?>
                  <option value="<?php echo $m; ?>" <?php echo ((int)date('n')===$m)?'selected':''; ?>><?php echo $label; ?></option>
                <?php endfor; ?>
              </select>
              <select id="pay_year" class="form-select form-select-sm" style="width:auto">
                <?php $y=(int)date('Y'); for($i=$y-3;$i<=$y+1;$i++): ?>
                  <option value="<?php echo $i; ?>" <?php echo ($i===$y)?'selected':''; ?>><?php echo $i; ?></option>
                <?php endfor; ?>
              </select>
              <button id="btnGeneratePayroll" class="btn btn-sm btn-primary">Generate</button>
              <button id="btnExportPayroll" class="btn btn-sm btn-outline-secondary">Export CSV</button>
              <button id="btnPayrollReport" class="btn btn-sm btn-outline-dark"><i class="bi bi-bar-chart"></i> Monthly Report</button>
            </div>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-sm align-middle" id="payroll-table">
                <thead><tr><th>Employee</th><th>Gross</th><th>OT</th><th>Allowances</th><th>Advances</th><th>Deductions</th><th>Net</th><th>Paid On</th><th>Actions</th></tr></thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Monthly Report Modal -->
  <div class="modal fade" id="payReportModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Payroll Monthly Report</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="row g-2 mb-3">
            <div class="col-12">
              <div id="payReportPeriod" class="fw-semibold"></div>
            </div>
            <div class="col-12">
              <div class="row text-center">
                <div class="col-6 col-md-3"><div class="small text-muted">Gross Total</div><div id="repGross" class="fs-6 fw-bold">0</div></div>
                <div class="col-6 col-md-3"><div class="small text-muted">OT</div><div id="repInc" class="fs-6 fw-bold">0</div></div>
                <div class="col-6 col-md-3"><div class="small text-muted">Allowances</div><div id="repAll" class="fs-6 fw-bold">0</div></div>
                <div class="col-6 col-md-3"><div class="small text-muted">Advances</div><div id="repAdv" class="fs-6 fw-bold">0</div></div>
                <div class="col-6 col-md-3 mt-2"><div class="small text-muted">Deductions</div><div id="repDed" class="fs-6 fw-bold">0</div></div>
                <div class="col-6 col-md-3 mt-2"><div class="small text-muted">Net Total</div><div id="repNet" class="fs-6 fw-bold">0</div></div>
                <div class="col-6 col-md-3 mt-2"><div class="small text-muted">Paid Count</div><div id="repPaidCnt" class="fs-6 fw-bold">0</div></div>
                <div class="col-6 col-md-3 mt-2"><div class="small text-muted">Unpaid Count</div><div id="repUnpaidCnt" class="fs-6 fw-bold">0</div></div>
              </div>
            </div>
          </div>
          <div class="table-responsive border rounded">
            <table class="table table-sm mb-0">
              <thead class="table-light">
                <tr>
                  <th>Employee</th>
                  <th class="text-end">Gross</th>
                  <th class="text-end">OT</th>
                  <th class="text-end">Allowances</th>
                  <th class="text-end">Advances</th>
                  <th class="text-end">Deductions</th>
                  <th class="text-end">Net</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody id="payReportTbody"></tbody>
            </table>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" id="btnReportPrint" class="btn btn-primary"><i class="bi bi-printer"></i> Print / PDF</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

  <input type="hidden" id="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>" />

  <!-- Employee Modal -->
  <div class="modal fade" id="empModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Employee</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form id="empForm">
          <div class="modal-body">
            <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
            <input type="hidden" name="id" id="empId">
            <div class="mb-2">
              <label class="form-label">Code</label>
              <input type="text" class="form-control" name="emp_code" id="emp_code" readonly>
            </div>
            <div class="mb-2">
              <label class="form-label">Full Name</label>
              <input type="text" class="form-control" name="full_name" id="emp_name" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Employee ID No</label>
              <input type="text" class="form-control" name="id_no" id="emp_id_no">
            </div>
            <div class="mb-2">
              <label class="form-label">Phone</label>
              <input type="text" class="form-control" name="phone" id="emp_phone">
            </div>
            <div class="mb-2">
              <label class="form-label">Email</label>
              <input type="email" class="form-control" name="email" id="emp_email">
            </div>
            <div class="mb-2">
              <label class="form-label">Address</label>
              <textarea class="form-control" name="address" id="emp_address" rows="2"></textarea>
            </div>
            <div class="mb-2">
              <label class="form-label">Branch</label>
              <select class="form-select" name="branch_id" id="emp_branch"></select>
            </div>
            <div class="mb-2">
              <label class="form-label">Designation</label>
              <select class="form-select" name="designation_id" id="emp_designation_id"></select>
            </div>
            <div class="mb-2">
              <label class="form-label">Base Salary</label>
              <input type="number" step="0.01" class="form-control" name="base_salary" id="emp_salary" value="0">
            </div>
            <div class="mb-2">
              <label class="form-label">Upload ID Copy (Image/PDF)</label>
              <input type="file" class="form-control" name="id_copy" id="emp_id_copy" accept="image/*,application/pdf">
            </div>
            <div class="form-check">
              <input class="form-check-input" type="checkbox" id="emp_active" name="is_active" checked>
              <label class="form-check-label" for="emp_active">Active</label>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Save</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Advance Modal -->
  <div class="modal fade" id="advModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header"><h5 class="modal-title">Add Advance</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <form id="advForm">
          <div class="modal-body">
            <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
            <input type="hidden" name="id" id="advId">
            <div class="mb-2">
              <label class="form-label">Employee</label>
              <select class="form-select" name="employee_id" id="adv_emp" required></select>
            </div>
            <div class="mb-2">
              <label class="form-label">Date</label>
              <input type="date" class="form-control" name="adv_date" id="adv_date" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Amount</label>
              <input type="number" step="0.01" class="form-control" name="amount" id="adv_amount" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Notes</label>
              <input type="text" class="form-control" name="notes" id="adv_notes">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Save</button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Deduction Modal -->
  <div class="modal fade" id="dedModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header"><h5 class="modal-title">Add Deduction</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <form id="dedForm">
          <div class="modal-body">
            <input type="hidden" name="csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
            <input type="hidden" name="id" id="dedId">
            <div class="mb-2">
              <label class="form-label">Employee</label>
              <select class="form-select" name="employee_id" id="ded_emp" required></select>
            </div>
            <div class="mb-2">
              <label class="form-label">Date</label>
              <input type="date" class="form-control" name="ded_date" id="ded_date" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Amount</label>
              <input type="number" step="0.01" class="form-control" name="amount" id="ded_amount" required>
            </div>
            <div class="mb-2">
              <label class="form-label">Reason</label>
              <input type="text" class="form-control" name="reason" id="ded_reason">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Save</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const $empTbody = $('#emp-table tbody');
  const csrf = $('#csrf').val();
  const $branchFilter = $('#empBranchFilter');
  const fmtLKR = v => Number(v||0).toLocaleString('en-LK',{style:'currency',currency:'LKR'});

  function loadBranches(sel){
    $.get('api/branches.php', { action:'list' }, function(res){
      const opts = ['<option value="">-- Select Branch --</option>'];
      (res.data||[]).filter(b=>String(b.is_active) === '1' || b.is_active===1).forEach(b=>{
        opts.push(`<option value="${b.id}">${$('<div>').text(b.name).html()}</option>`);
      });
      $(sel).html(opts.join(''));
    });
  }

  function loadEmployeesIntoSelect($sel){
    $.get('api/employees.php', { action:'list', only_active: 1 }, function(res){
      const opts = ['<option value="">-- Select Employee --</option>'];
      (res.data||[]).forEach(e=> opts.push(`<option value="${e.id}">${$('<div>').text(e.full_name||'').html()}</option>`));
      $sel.html(opts.join(''));
    });
  }

  function fetchEmployees(){
    const params = { action:'list' };
    const bf = $branchFilter.val(); if (bf) params.branch_id = bf;
    $.get('api/employees.php', params, function(res){
      // Sync global cache so other modules (advances/deductions/OT) see the latest employees
      window.EMP_CACHE = res.data || [];
      $empTbody.empty();
      (res.data||[]).forEach(e=>{
        const tr = $('<tr>');
        tr.append(`<td>${$('<div>').text(e.emp_code||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(e.full_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(e.phone||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(e.branch_name||'').html()}</td>`);
        tr.append(`<td>${$('<div>').text(e.designation_name||e.designation||'').html()}</td>`);
        tr.append(`<td class="text-end">${Number(e.base_salary||0).toLocaleString('en-LK',{style:'currency',currency:'LKR'})}</td>`);
        tr.append(`<td>${(e.is_active? 'Active':'Inactive')}</td>`);
        tr.append(`<td>
          <button class="btn btn-sm btn-primary me-2 btn-emp-edit" data-id="${e.id}" title="Edit"><i class="bi bi-pencil"></i></button>
          <button class="btn btn-sm btn-danger btn-emp-del" data-id="${e.id}" title="Delete"><i class="bi bi-trash"></i></button>
        </td>`);
        $empTbody.append(tr);
      });
      // Notify listeners if needed
      $(document).trigger('employees:updated');
    });
  }

  function loadDesignations(sel){
    $.get('api/designations.php', { action:'list', only_active: 1 }, function(res){
      const opts = ['<option value="">-- Select Designation --</option>'];
      (res.data||[]).forEach(d=>{ opts.push(`<option value="${d.id}">${$('<div>').text(d.name).html()}</option>`); });
      $(sel).html(opts.join(''));
    });
  }

  // Add Employee
  $('#btnAddEmployee').on('click', function(){
    $('#empForm')[0].reset();
    $('#empId').val('');
    $('#emp_active').prop('checked', true);
    loadBranches('#emp_branch');
    loadDesignations('#emp_designation_id');
    // Auto-generate employee code
    $.get('api/employees.php', { action:'generate_code' }, function(res){ if(res && res.code) $('#emp_code').val(res.code); });
    $('#empModal').modal('show');
  });

  // Edit Employee
  $('#emp-table').on('click', '.btn-emp-edit', function(){
    const id = $(this).data('id');
    $.get('api/employees.php', { action:'get', id }, function(res){
      const e = res.data||{};
      $('#empId').val(e.id);
      $('#emp_code').val(e.emp_code||'');
      $('#emp_name').val(e.full_name||'');
      $('#emp_id_no').val(e.id_no||'');
      $('#emp_phone').val(e.phone||'');
      $('#emp_email').val(e.email||'');
      $('#emp_address').val(e.address||'');
      $('#emp_salary').val(e.base_salary||0);
      loadDesignations('#emp_designation_id');
      $('#emp_active').prop('checked', !!parseInt(e.is_active));
      loadBranches('#emp_branch');
      // ensure branch is set after options load
      $(document).one('ajaxStop', function(){
        $('#emp_branch').val(e.branch_id||'');
        $('#emp_designation_id').val(e.designation_id||'');
      });
      $('#empModal').modal('show');
    });
  });

  // Delete Employee
  $('#emp-table').on('click', '.btn-emp-del', function(){
    const id = $(this).data('id');
    if(!confirm('Delete this employee?')) return;
    $.post('api/employees.php?action=delete', { id, csrf }, function(){ fetchEmployees(); });
  });

  // Save Employee
  $('#empForm').on('submit', function(e){
    e.preventDefault();
    const formEl = this;
    const data = new FormData(formEl);
    const action = $('#empId').val() ? 'update':'create';
    $.ajax({
      url: 'api/employees.php?action='+action,
      method: 'POST',
      data: data,
      contentType: false,
      processData: false,
      success: function(){ $('#empModal').modal('hide'); fetchEmployees(); },
      error: function(xhr){ alert(xhr.responseJSON?.message || 'Error'); }
    });
  });

  // Initial load
  // populate branch filter then fetch
  loadBranches('#empBranchFilter');
  $(document).one('ajaxStop', function(){ $branchFilter.prepend('<option value="">All Branches</option>'); fetchEmployees(); });
  $branchFilter.on('change', fetchEmployees);

  // When employees update, refresh dropdowns used by other salary components
  $(document).on('employees:updated', function(){
    loadEmployeesIntoSelect($('#adv_emp'));
    loadEmployeesIntoSelect($('#ded_emp'));
    loadEmployeesIntoSelect($('#inc_emp'));
  });

  // Advances/Deductions are handled in global assets/js/app.js to avoid duplicate bindings
})();
</script>
