<div id="daily_expense_modal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog">
    <form action="<?= base_url('admin/expense/add') ?>" method="post" class="modal-content">
      <div class="modal-body">
        <h4 class="text-center mb-3">Add Daily Expense</h4>
    <!-- CSRF Token -->
    <input type="hidden" name="<?= $this->security->get_csrf_token_name(); ?>" 
           value="<?= $this->security->get_csrf_hash(); ?>" />
        <div class="form-group">
          <label>Expense Date</label>
          <input type="date" name="date" class="form-control" value="<?= date('Y-m-d') ?>" required>
        </div>

        <div class="form-group">
          <label>Expense Type</label>
          <select name="expense_type_id" id="expense_type_id" class="form-control" required>
            <option value="">Select</option>
            <?php foreach ($expense_types as $et): ?>
              <option value="<?= $et->id ?>"><?= $et->expense_type ?></option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="form-group">
          <label>Sub Expense Type</label>
          <select name="sub_expense_type_id" id="sub_expense_type_id" class="form-control" required>
            <option value="">Select Sub Type</option>
          </select>
        </div>

        <div class="form-group">
          <label>Rate</label>
          <input type="number" name="rate" id="rate" class="form-control" placeholder="Optional">
        </div>

        <div class="form-group">
          <label>Quantity</label>
          <input type="number" name="quantity" id="qty" class="form-control" placeholder="Optional">
        </div>

        <div class="form-group">
          <label>Amount</label>
          <input type="number" name="amount" id="amount" class="form-control" required>
        </div>

        <div class="form-group">
          <label>Note</label>
          <input type="text" name="note" class="form-control">
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-success">Save</button>
      </div>
    </form>
  </div>
</div>

<script>
$(document).ready(function () {
  $('#expense_type_id').change(function () {
    var typeId = $(this).val();
    if (typeId) {
      $.get('<?= base_url('admin/Expense/get_sub_expense_types/') ?>' + typeId, function (data) {
        let options = '<option value="">Select Sub Type</option>';
        $.each(JSON.parse(data), function (_, row) {
          options += `<option value="${row.id}">${row.sub_expense_type}</option>`;
        });
        $('#sub_expense_type_id').html(options);
      });
    }
  });

  $('#rate, #qty').on('input', function () {
    let rate = parseFloat($('#rate').val()) || 0;
    let qty  = parseFloat($('#qty').val()) || 0;
    $('#amount').val((rate * qty).toFixed(2));
  });
});
</script>
