<?php
include("../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$amount = '';
$date = '';
$amount= '';
$paid_to= '';
$payment_type= '';
$chq_date= '';
$chq_no= '';
$bank_id= '';
$bility_no= '';
$city= '';
$carton= '';
$rate= '';
$description= '';
$created_by= '';
$create_date= '';
$description = '';

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
extract($_REQUEST);

if (isset($_POST) && !empty($_GET['delete'])) {
    ExpenseTaxSetup::DeleteExpenseTaxSetup($_GET['delete']);
    header("Location: " . PROJECT_ADMIN_URL . "expense_tax_setup.php?view");
    exit();
}


if ($datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-30 days"));
} else {
    $datefrom = date("Y-m-d", strtotime($datefrom));
}
if ($dateto == "") {
    $dateto = date('Y-m-d');
} else {
    $dateto = date("Y-m-d", strtotime($dateto));
}
$datefrom = date("d-m-Y", strtotime($datefrom));
$dateto = date("d-m-Y", strtotime($dateto));

$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo = date("Y-m-d", strtotime($dateto));

//$filterE = " WHERE DATE_FORMAT(create_date,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(create_date,'%Y-%m-%d')<='$qryTo' ";
$filterE = " WHERE DATE_FORMAT(`date`, '%Y-%m-%d') >= '$qryDate' AND DATE_FORMAT(`date`, '%Y-%m-%d') <= '$qryTo' ";


//if($_SESSION['sess_type'] == 'profile'){
//	$uid = $_SESSION['sess_userid'];
//	$filterE .= " and user_id = '$uid' ";	
//}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
    <style>
        table{
            font-size:18px;
        }
    </style>
</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Add Supplier Expense</h3>
            </div>
            <hr>
            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true
                    });
                    $('#datepicker2').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true
                    });
                  $('#datepicker4').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true
                    });
                });
            </script>
           <?php if (isset($_GET['view'])): ?>
            <form action="" method="get" name="search"
                  id="searchfrm">
                <table class="table">
                    <tr>
                        <td class="col l4">Date From<br>
                            <input type="text" name="datefrom" id="datepicker1"
                                   placeholder="Date From"
                                   value="<?= $datefrom ?>" class="datepicker form-control"/>
                            <input type="hidden" name="view" id="view" class="form-control"/>
                        </td>
                        <td class="col l4"> Date To<br>
                            <input type="text" name="dateto" id="datepicker2"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="datepicker form-control"/>
                        </td>
                        <td class="col l4">&nbsp;<br>
                            <button type="submit" class="btn waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>
                        </td>
                    </tr>
                </table>
            </form>
          <?php endif; ?>
            
            <?php if ($_SESSION['sess_role'] == 'VEC') {
                if (isset($_GET['view'])) { ?>
                    <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;" href="?add">Add Other Expense <i
                            class="mdi-content-add-box"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>
            <?php
          if (isset($_GET['add'])) {
    $voucher_date = $_POST['date'] ?? date('Y-m-d');
    $prefix = date('Ymd', strtotime($voucher_date));
    $filter = "WHERE voucher_no LIKE '$prefix%' ORDER BY id DESC LIMIT 1";
    $vouchers = ExpenseTaxSetup::GetExpenseTaxSetupList($filter);

    if (!empty($vouchers[0]->voucher_no)) {
        $lastNo = intval(substr($vouchers[0]->voucher_no, 8));
        $voucherNo = $prefix . str_pad($lastNo + 1, 3, '0', STR_PAD_LEFT);
    } else {
        $voucherNo = $prefix . "001";
    }
}
            if (isset($_GET['add'])) {
                if (empty($lastupdated)) {
                    $lastupdated = date('Y-m-d');
                }
            if (isset($_POST) && !empty($_POST)) {
                extract($_REQUEST);
                $data = [];
                $data['date']         = date('Y-m-d', strtotime($lastupdated));
                $data['category_id']  = $category_id;
                $data['amount']       = $amount;
              	$data['bill_no'] = !empty($bill_no) ? $bill_no : null;
                $data['supplier_id'] = $_POST['supplier_id'];
				$data['paid_to'] = null;
                $data['payment_type'] = $payment_type;
              	$data['wht_paid'] = 0;

                // Only set cheque fields if payment type is cheque
                if ($payment_type === 'cheque') {
                    $data['chq_date'] = !empty($chq_date) ? date('Y-m-d', strtotime($chq_date)) : null;
                    $data['chq_no']   = !empty($chq_no) ? $chq_no : null;
                    $data['bank_id']  = !empty($bank_id) ? $bank_id : null;
                }

                // You may optionally exclude cheque fields on cash to avoid sending nulls
                else {
                    unset($data['chq_date'], $data['chq_no'], $data['bank_id']);
                }
				$data['expense_type']      = $expense_type;
                // Bilty fields
                $data['bility_no']   = !empty($bility_no) ? $bility_no : null;
                $data['city']        = !empty($city) ? $city : null;
                $data['carton']      = !empty($carton) ? (int)$carton : null;
                $data['rate']        = !empty($rate) ? $rate : null;

                // Other metadata
                $data['description']   = !empty($description) ? $description : null;
                $data['created_by']    = $_SESSION['sess_userid'];
                $data['create_date']   = date('Y-m-d H:i:s');
				$data['wht'] = isset($_POST['wht']) ? (int)$_POST['wht'] : 0;
              	$data['issuer_id']   = isset($_POST['issuer_id']) ? (int)$_POST['issuer_id'] : null;
				$data['approver_id'] = isset($_POST['approver_id']) ? (int)$_POST['approver_id'] : null;
              	$data['voucher_no'] = isset($_POST['voucher_no']) ? $_POST['voucher_no'] : null;


              // ✅ Add this to set the voucher_no based on the selected date
if (isset($_POST['lastupdated'])) {
    $voucherDate = date('Y-m-d', strtotime($_POST['lastupdated']));
    $data['voucher_no'] = ExpenseTaxSetup::GenerateVoucherNo($voucherDate);
}

                $errors = array();
              
           //   echo "<pre>";
			//print_r($data);
		//echo "</pre>";
                // Validate the input

                if ($amount == 0)
                    array_push($errors, "Please enter amount");

            if (count($errors) == 0) {
                $q = ExpenseTaxSetup::AddExpenseTaxSetup($data);
            if ($q) {
                $output = '';
                //header("Location: ?view&sucess"); ?>
                <script>window.location.href = 'expense_tax_setup.php?view&sucess'</script>

            <?php
            echo "<div id='card-alert' class='card green lighten-5'>
                      <div class='card-content green-text'>
                        <p>SUCCESS : <strong>Attention! </strong>Submitted!</p>
                      </div>
                      <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
            } else {
                $output = '';
                echo "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>Some error occurred!</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
            }
            } else {
                //Prepare errors for output
                foreach ($errors as $val) {
                    $output .= "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>$val</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                }
            }
            }
            ?>
                <div class="row">
                    <form action="" method="post" id="expense_tax_setup_form" novalidate="novalidate">
                        <div class="col-sm-12 form-group">
                            <?php echo $output; ?>
                            <div class="col-sm-8">
                                <div class="row">
                                    <span>(*) Mark Fields are mandatory</span><br/><br/>
                                </div>
                              
                              <div class="row margin">
                                  <div class="input-field col s12">
                                      <label for="wht" class="control-label">Apply WHT *</label><br/>
                                      <select class="form-control" name="wht" id="wht" required>
                                          <option value="0" <?= ($wht == 0) ? 'selected' : '' ?>>No</option>
                                          <option value="1" <?= ($wht == 1) ? 'selected' : '' ?>>Yes</option>
                                      </select>
                                  </div>
                              </div>
                              
                               <div class="row margin">
  <div class="input-field col s12">
    <label for="voucher_no" class="active">Voucher No</label>
    <input type="text" name="voucher_no" id="voucher_no" class="form-control" value="<?= $voucherNo ?>" readonly />
  </div>
</div>
                              <div class="row margin">
                                    <div class="input-field col s12">
                                        <input class="form-control" type="text" id="datepicker" name="lastupdated"
                                               value='<?php echo date('d-m-Y', strtotime($lastupdated)); ?>'/>
                                        <label for="datepicker" class="control-label">Date *</label>
                                    </div>
                                </div>
                                <div class="row margin">
                                    <div class="input-field col s12">
                                        <select class="form-control" name="category_id" id="category_id">
                                            <?php
                                            // Fetch all active categories
                                            $allCats = ExpenseTaxCategorySetup::GetExpenseTaxCategorySetupList("WHERE status = 'active' ORDER BY parent_id, name");

                                            $parents = [];
                                            $children = [];

                                            // Separate parents and children
                                            foreach ($allCats as $cat) {
                                                if ($cat->parent_id == 0) {
                                                    $parents[$cat->id] = $cat;
                                                } else {
                                                    $children[$cat->parent_id][] = $cat;
                                                }
                                            }

                                            // Render grouped dropdown
                                            foreach ($parents as $parent_id => $parent) {
                                                if (!isset($children[$parent_id])) continue; // Skip if no children

                                                echo "<optgroup label='" . ucwords($parent->name) . "'>";
                                                foreach ($children[$parent_id] as $child) {
                                                    $selected = ($child->id == $category_id) ? 'selected' : '';
                                                    echo "<option value='{$child->id}' {$selected}>" . ucwords($child->name) . "</option>";
                                                }
                                                echo "</optgroup>";
                                            }
                                            ?>
                                        </select>
                                        <label for="category_id" class="control-label">Category</label>
                                    </div>
                                </div>

                                
                                <div class="row margin">
                                    <div class="input-field col s12">
                                        <input class="form-control" type="number" id="amount" maxlength="250"
                                               name="amount"
                                               value='<?php echo $amount; ?>'/>
                                        <label for="amount" class="control-label">Amount *</label>
                                    </div>
                                </div>
                              
                              <div class="row margin">
                                  <div class="input-field col s12">
                                      <input type="text" id="bill_no" name="bill_no" value="<?= $bill_no ?? '' ?>" class="form-control" />
                                      <label for="bill_no">Bill No</label>
                                  </div>
                              </div>
                              
                               <div class="row margin">
                                  <div class="input-field col s12">
                                      <label for="supplier_id" class="control-label">Supplier *</label><br/>
                                      <select class="form-control" name="supplier_id" id="supplier_id" required>
                                          <option value="">-- Select Supplier --</option>
                                          <?php
                                          $supplierFilter = "WHERE status = 'active'";
                                          $suppliers = SupplierSetup::GetSupplierSetupList($supplierFilter);
                                          foreach ($suppliers as $sup) {
                                              echo "<option value='{$sup->id}'>{$sup->name} ({$sup->code})</option>";
                                          }
                                          ?>
                                      </select>
                                  </div>
                              </div>
                              

                              <input type="hidden" name="paid_to" value="">

                              
                              
                              <div class="input-field col s12">
                              <label for="payment_type" class="control-label">Payment Type *</label><br/>
                              <select class="form-control" name="payment_type" id="payment_type" required>
                                 
                                  <option value="cash" <?= ($payment_type == 'cash') ? 'selected' : '' ?>>Cash</option>
                                  <option value="cheque" <?= ($payment_type == 'cheque') ? 'selected' : '' ?>>Cheque</option>
                              </select>
                          </div>
                              
                              
                              <!-- CHQ Date -->
                                <div class="row margin chq-field" style="display:none;">
                                    <div class="input-field col s12">
                                        <input class="form-control" type="text" id="datepicker4" name="chq_date"
                                               value="<?= !empty($chq_date) ? date('d-m-Y', strtotime($chq_date)) : date('d-m-Y') ?>" />
                                        <label for="datepicker4" class="control-label">CHQ Date *</label>
                                    </div>
                                </div>

                                <!-- CHQ Number -->
									<div class="row margin chq-field" style="display:none;">

                                    <div class="input-field col s12">
                                        <input class="form-control" type="text" id="chq_no" name="chq_no" value="<?= $chq_no ?? '' ?>" />
                                        <label for="chq_no" class="control-label">CHQ No *</label>
                                    </div>
                                </div>

                               <!-- Bank Dropdown -->
									<div class="row margin chq-field" style="display:none;">

                                    <div class="input-field col s12">
                                        <label for="bank_id" class="control-label">Select Bank *</label><br/>
                                        <select class="form-control" name="bank_id" id="bank_id">
                                            <option value="">-- Select Bank --</option>
                                            <?php
                                            $bankList = BankSetup::GetBankSetupList(" WHERE status = 'active' ORDER BY bank_name ");
                                            if ($bankList) {
                                                foreach ($bankList as $bank) {
                                                    $selected = ($bank_id == $bank->id) ? 'selected' : '';
                                                    echo "<option value='{$bank->id}' {$selected}>{$bank->bank_name}</option>";
                                                }
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                              
                              <div class="row margin">
                                <div class="input-field col s12">
                                    <label for="expense_type" class="control-label">Expense Type *</label><br/>
                                    <select class="form-control" name="expense_type" id="expense_type" required>
                                       
                                        <option value="normal" <?= ($expense_type == 'normal') ? 'selected' : '' ?>>Normal</option>
                                        <option value="bility" <?= ($expense_type == 'bility') ? 'selected' : '' ?>>Bilty</option>
                                    </select>
                                </div>
                            </div>

                              <!-- Bilty No -->
                                <div class="row margin bilty-fields" style="display:none;">
                                    <div class="input-field col s12">
                                        <input type="text" id="bility_no" name="bility_no" value="<?= $bility_no ?? '' ?>" class="form-control" />
                                        <label for="bility_no">Bilty No</label>
                                    </div>
                                </div>

                                <!-- City -->
                                <div class="row margin bilty-fields" style="display:none;">
                                    <div class="input-field col s12">
                                        <input type="text" id="city" name="city" value="<?= $city ?? '' ?>" class="form-control" />
                                        <label for="city">City</label>
                                    </div>
                                </div>

                                <!-- Number of Cartons -->
                                <div class="row margin bilty-fields" style="display:none;">
                                    <div class="input-field col s12">
                                        <input type="number" id="carton" name="carton" value="<?= $carton ?? '' ?>" class="form-control" />
                                        <label for="carton">No. of Cartons</label>
                                    </div>
                                </div>

                                <!-- Rate -->
                                <div class="row margin bilty-fields" style="display:none;">
                                    <div class="input-field col s12">
                                        <input type="text" id="rate" name="rate" value="<?= $rate ?? ''  ?>" readonly class="form-control" />
                                        <label for="rate">Rate</label>
                                    </div>
                                </div>

                              
                              

                              
                                <div class="row margin">
                                    <div class="input-field col s12">
                                <textarea class="materialize-textarea" name="description"
                                          id="description"><?php echo $description; ?></textarea>
                                        <label for="description" class="control-label">Description </label>
                                    </div>
                                </div>
                              <!-- issuer and approver fields -->
<?php
  // Default issuer ID for "Asad Uddin"
  if (!isset($issuer_id)) {
      $defaultIssuer = EmployeeAuthoritySetup::GetEmployeeAuthorityByName('Asad Uddin');
      $issuer_id = $defaultIssuer->id ?? '';
  }
?>

<div class="row margin">
  <div class="input-field col s12">
    <label for="issuer_id" class="control-label">Issuer *</label><br/>
    <select class="form-control" name="issuer_id" id="issuer_id" required>
      <option value="">-- Select Issuer --</option>
      <?php
      $filter = "WHERE category = 'issuer' AND status = 'active'";
      $issuers = EmployeeAuthoritySetup::GetEmployeeAuthorityList($filter);
      foreach ($issuers as $issuer) {
          $selected = ($issuer->id == ($issuer_id ?? '')) ? 'selected' : '';
          echo "<option value='{$issuer->id}' $selected>{$issuer->name}</option>";
      }
      ?>
    </select>
  </div>
</div>

<?php
  // Default approver ID for "Asif Hussain"
  if (!isset($approver_id)) {
      $defaultApprover = EmployeeAuthoritySetup::GetEmployeeAuthorityByName('Asif Hussain');
      $approver_id = $defaultApprover->id ?? '';
  }
?>

<div class="row margin">
  <div class="input-field col s12">
    <label for="approver_id" class="control-label">Approver *</label><br/>
    <select class="form-control" name="approver_id" id="approver_id" required>
      <option value="">-- Select Approver --</option>
      <?php
      $filter = "WHERE category = 'approver' AND status = 'active'";
      $approvers = EmployeeAuthoritySetup::GetEmployeeAuthorityList($filter);
      foreach ($approvers as $approver) {
          $selected = ($approver->id == ($approver_id ?? '')) ? 'selected' : '';
          echo "<option value='{$approver->id}' $selected>{$approver->name}</option>";
      }
      ?>
    </select>
  </div>
</div>                         <div class="row margin">
                                    <div class="input-field col s12">
                                        <button id="btnsubmit" type="submit" class="btn waves-effect waves-light">Submit
                                        </button>
                                        <button type="button" class="btn waves-effect waves-light"
                                                onclick="location.href='expense_tax_setup.php?view'">Cancel
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <?php
            } // add close

           


            if (isset($_GET['edit']) && !empty($_POST)) {
                extract($_REQUEST);
               $id = $_GET['id'];
              $existingVoucher = ExpenseTaxSetup::GetExpenseTaxSetupById($id);
                $data = [];
                $data['date']          = date('Y-m-d', strtotime($lastupdated));
                $data['category_id']   = $category_id;
                $data['amount']        = $amount;
                $data['paid_to']       = $paid_to;
              	$data['bill_no']       = $bill_no;
             //   $data['payment_type']  = $payment_type;
              	$data['supplier_id'] = $_POST['supplier_id'];

                 if ($payment_type === 'cheque') {
                    $data['chq_date'] = !empty($chq_date) ? date('Y-m-d', strtotime($chq_date)) : null;
                    $data['chq_no']   = !empty($chq_no) ? $chq_no : null;
                    $data['bank_id']  = !empty($bank_id) ? $bank_id : null;
                }

                // You may optionally exclude cheque fields on cash to avoid sending nulls
                else {
                    unset($data['chq_date'], $data['chq_no'], $data['bank_id']);
                }
				$data['expense_type']      = $expense_type;
                $data['bility_no']     = $bility_no ?? null;
                $data['city']          = $city ?? null;
                $data['carton']        = $carton ?? null;
                $data['rate']          = $rate ?? null;
                $data['description']   = $description ?? null;
                $data['created_by']    = $_SESSION['sess_userid'];
                $data['create_date']   = date('Y-m-d H:i:s');
				$data['wht'] = isset($_POST['wht']) ? (int)$_POST['wht'] : 0;
              	$data['issuer_id']   = isset($_POST['issuer_id']) ? (int)$_POST['issuer_id'] : null;
				$data['approver_id'] = isset($_POST['approver_id']) ? (int)$_POST['approver_id'] : null;
               if ($existingVoucher) {
                  $oldDate = $existingVoucher->date;
                  $newDate = date('Y-m-d', strtotime($lastupdated));

                  if ($oldDate !== $newDate) {
                      // Regenerate only if date changed
                      $data['voucher_no'] = ExpenseTaxSetup::GenerateVoucherNo($newDate);
                  } else {
                      $data['voucher_no'] = $existingVoucher->voucher_no;
                  }
              }

                $errors = array();
                // Validate the input

                if ($amount == 0)
                    array_push($errors, "Please enter amount");

                if (count($errors) == 0) {
                    $q = ExpenseTaxSetup::UpdateExpenseTaxSetup($id, $data);
                    if ($q) {
                        $output = '';
                        //header("Location: ?view&sucess"); ?>
                        <script>window.location.href = 'expense_tax_setup.php?view&sucess'</script>

                        <?php
                        echo "<div id='card-alert' class='card green lighten-5'>
                      <div class='card-content green-text'>
                        <p>SUCCESS : <strong>Attention! </strong>Submitted!</p>
                      </div>
                      <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                    } else {
                        $output = '';
                        echo "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>Some error occurred!</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                    }
                } else {
                    //Prepare errors for output
                    foreach ($errors as $val) {
                        $output .= "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>$val</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                    }
                }
            }
            if (isset($_GET['edit'])) {
                $id = $_GET['id'];
                if (empty($_POST)) {
                    $qry = ExpenseTaxSetup::GetExpenseTaxSetupById($id);

                    $lastupdated = $qry->date;
                    $category_id = $qry->category_id;
                    $amount = $qry->amount;
                	$bill_no = $qry->bill_no;
                    $paid_to = $qry->paid_to;
                  	$supplier_id = $qry->supplier_id;
                    $payment_type = $qry->payment_type;
                    $chq_date = $qry->chq_date;
                    $chq_no = $qry->chq_no;
                    $bank_id = $qry->bank_id;
					$expense_type = $qry->expense_type;
                    $bility_no = $qry->bility_no;
                    $city = $qry->city;
                    $carton = $qry->carton;
                    $rate = $qry->rate;
                  	$wht = $qry->wht ?? 0;
                    $description = $qry->description;
                  $issuer_id   = $qry->issuer_id;
                  $approver_id = $qry->approver_id;
                }
                if ($_REQUEST['id'] && isset($_REQUEST['v'])) {
                    ?>
                    <div class="row">
                        <!--  The form that will be parsed by jQuery before submit  -->
                        <div class="col-sm-12 form-group">
                            <div class="col-sm-8">
                                <div class="row">
                                    <div class="col s6">Category Name:</div>
                                    <div class="col s6"><?php echo $ExpCatName; ?></div>
                                </div>
                                <div class="row">
                                    <div class="col s6">Date:</div>
                                    <div class="col s6"><?php echo date('d-m-Y', strtotime($lastupdated)); ?></div>
                                </div>
                                <div class="row">
                                    <div class="col s6">Amount:</div>
                                    <div class="col s6"><?php echo $amount; ?></div>
                                </div>
                                <div class="row">
                                    <div class="col s6">Description:</div>
                                    <div class="col s6"><?php echo $description; ?></div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php } else {
                    ?>
                    <div class="row">
                        <!--  The form that will be parsed by jQuery before submit  -->
                        <form action="?edit&id=<?= $id ?>" method="post" id="expense_tax_setup_form" novalidate>
                           <div class="row margin">
                                  <div class="input-field col s12">
                                      <label for="wht" class="control-label">Apply WHT *</label><br/>
                                      <select class="form-control" name="wht" id="wht" required>
                                          <option value="0" <?= ($wht == 0) ? 'selected' : '' ?>>No</option>
                                          <option value="1" <?= ($wht == 1) ? 'selected' : '' ?>>Yes</option>
                                      </select>
                                  </div>
                              </div>
                          
                            <div class="row margin">
    <div class="input-field col s12">
        <input type="text" id="voucher_no" name="voucher_no" class="form-control" value="<?= $qry->voucher_no ?>" readonly>
        <label for="voucher_no" class="active">Voucher Number</label>
    </div>
</div>
                          
                          
    <div class="row margin">
        <div class="input-field col s12">
            <input type="text" id="datepicker" name="lastupdated" value="<?= date('d-m-Y', strtotime($lastupdated)) ?>" />
            <label for="datepicker">Date *</label>
        </div>
    </div>

    <div class="row margin">
        <div class="input-field col s12">
            <select name="category_id" id="category_id">
                <?php
                $categories = ExpenseTaxCategorySetup::GetExpenseTaxCategorySetupList("WHERE parent_id <> 0 ORDER BY name");
                foreach ($categories as $cat) {
                    $selected = ($cat->id == $category_id) ? 'selected' : '';
                    echo "<option value='{$cat->id}' $selected>" . ucwords($cat->name) . "</option>";
                }
                ?>
            </select>
            <label for="category_id">Expense Category *</label>
        </div>
    </div>

    <div class="row margin">
        <div class="input-field col s12">
            <input type="number" name="amount" id="amount" value="<?= $amount ?>" />
            <label for="amount">Amount *</label>
        </div>
    </div>
                          
                          <div class="row margin">
                            <div class="input-field col s12">
                                <input type="text" id="bill_no" name="bill_no" value="<?= $bill_no ?? '' ?>" class="form-control" />
                                <label for="bill_no">Bill No</label>
                            </div>
                        </div>

 
                          
                         <div class="row margin">
                          <div class="input-field col s12">
                              <label for="supplier_id" class="control-label">Supplier *</label><br/>
                              <select class="form-control" name="supplier_id" id="supplier_id" required>
                                  <option value="">-- Select Supplier --</option>
                                  <?php
                                  $supplierFilter = "WHERE status = 'active'";
                                  $suppliers = SupplierSetup::GetSupplierSetupList($supplierFilter);
                                  foreach ($suppliers as $sup) {
                                      $selected = ($sup->id == $supplier_id) ? 'selected' : '';
                                      echo "<option value='{$sup->id}' $selected>{$sup->name} ({$sup->code})</option>";
                                  }
                                  ?>
                              </select>
                          </div>
                      </div>

    <div class="input-field col s12">
        <select name="payment_type" id="payment_type">
            <option value="">-- Select Payment Type --</option>
            <option value="cash" <?= ($payment_type == 'cash') ? 'selected' : '' ?>>Cash</option>
            <option value="cheque" <?= ($payment_type == 'cheque') ? 'selected' : '' ?>>Cheque</option>
        </select>
        <label for="payment_type">Payment Type *</label>
    </div>

    <div class="row margin chq-field" style="display:<?= $payment_type == 'cheque' ? 'block' : 'none' ?>">
        <div class="input-field col s12">
            <input type="text" id="datepicker4" name="chq_date" value="<?= !empty($chq_date) ? date('d-m-Y', strtotime($chq_date)) : '' ?>" />
            <label for="datepicker4">CHQ Date</label>
        </div>
    </div>

    <div class="row margin chq-field" style="display:<?= $payment_type == 'cheque' ? 'block' : 'none' ?>">
        <div class="input-field col s12">
            <input type="text" id="chq_no" name="chq_no" value="<?= $chq_no ?>" />
            <label for="chq_no">CHQ No</label>
        </div>
    </div>

    <div class="row margin chq-field" style="display:<?= $payment_type == 'cheque' ? 'block' : 'none' ?>">
        <div class="input-field col s12">
            <select name="bank_id" id="bank_id">
                <option value="">-- Select Bank --</option>
                <?php
                $banks = BankSetup::GetBankSetupList("WHERE status = 'active' ORDER BY bank_name");
                foreach ($banks as $bank) {
                    $selected = ($bank->id == $bank_id) ? 'selected' : '';
                    echo "<option value='{$bank->id}' $selected>{$bank->bank_name}</option>";
                }
                ?>
            </select>
            <label for="bank_id">Bank Name</label>
        </div>
    </div>
                          
                          
                           <div class="row margin">
                                <div class="input-field col s12">
                                    <label for="expense_type" class="control-label">Expense Type *</label><br/>
                                <select class="form-control" name="expense_type" id="expense_type" required>
                                  <?= $expense_type ?>
                                    <option value="">-- Select Expense Type --</option>
                                    <option value="normal" <?php echo ($expense_type == 'normal') ? 'selected' : ''; ?>>Normal</option>
                                    <option value="bility" <?php echo ($expense_type == 'bility') ? 'selected' : ''; ?>>Bilty</option>
                                </select>


                                </div>
                            </div>
                          
                          

    <!-- Bilty Fields -->
    <div class="row margin bilty-fields">
        <div class="input-field col s12">
            <input type="text" name="bility_no" value="<?= $bility_no ?>" />
            <label for="bility_no">Bilty No</label>
        </div>
    </div>

    <div class="row margin bilty-fields">
        <div class="input-field col s12">
            <input type="text" name="city" value="<?= $city ?>" />
            <label for="city">City</label>
        </div>
    </div>

    <div class="row margin bilty-fields">
        <div class="input-field col s12">
            <input type="number" name="carton" id="carton" value="<?= $carton ?>" />
            <label for="carton">Cartons</label>
        </div>
    </div>

    <div class="row margin bilty-fields">
        <div class="input-field col s12">
            <input type="text" name="rate" id="rate" value="<?= $rate ?>" readonly />
            <label for="rate">Rate</label>
        </div>
    </div>

    <div class="row margin">
        <div class="input-field col s12">
            <textarea class="materialize-textarea" name="description"><?= $description ?></textarea>
            <label for="description">Description</label>
        </div>
    </div>
                           <!-- issuer and approver fields -->
<div class="row margin">
  <div class="input-field col s12">
    <label for="issuer_id" class="control-label">Issuer *</label><br/>
    <select class="form-control" name="issuer_id" id="issuer_id" required>
      <option value="">-- Select Issuer --</option>
      <?php
              $filter = "WHERE category = 'issuer'AND status = 'active'";
      $issuers = EmployeeAuthoritySetup::GetEmployeeAuthorityList($filter);
      foreach ($issuers as $issuer) {
          $selected = ($issuer->id == ($issuer_id ?? '')) ? 'selected' : '';
          echo "<option value='{$issuer->id}' $selected>{$issuer->name}</option>";
      }
      ?>
    </select>
  </div>
</div>

<div class="row margin">
  <div class="input-field col s12">
    <label for="approver_id" class="control-label">Approver *</label><br/>
    <select class="form-control" name="approver_id" id="approver_id" required>
      <option value="">-- Select Approver --</option>
      <?php
      $filter = "WHERE category = 'approver' AND status = 'active'";
      $approvers = EmployeeAuthoritySetup::GetEmployeeAuthorityList($filter);
      foreach ($approvers as $approver) {
          $selected = ($approver->id == ($approver_id ?? '')) ? 'selected' : '';
          echo "<option value='{$approver->id}' $selected>{$approver->name}</option>";
      }
      ?>
    </select>
  </div>
</div>

    <div class="row margin">
        <div class="input-field col s12">
            <button type="submit" class="btn waves-effect waves-light">Submit</button>
            <button type="button" class="btn waves-effect waves-light" onclick="window.location='expense_tax_setup.php?view'">Cancel</button>
        </div>
    </div>
</form>
                    </div>
                <?php }
            }
            ?>
        </div>
    </div>
</div>
</div>
<?php include('includes/inc_footer.php'); ?>
<?php include('includes/inc_js.php'); ?>
<script type="application/javascript">
    $(document).ready(function () {
        var fewSeconds = 2;
        $('#btnsubmit').click(function () {
            // Ajax request
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });
    });
  
 $(document).ready(function () {
    // Trigger change handlers when DOM is ready
    toggleChequeFields();
    toggleBiltyFields();

    // Payment Type toggle
    $('#payment_type').on('change', function () {
        toggleChequeFields();
    });

    // Expense Type toggle
    $('#expense_type').on('change', function () {
        toggleBiltyFields();
    });

    function toggleChequeFields() {
        let paymentType = $('#payment_type').val();
        if (paymentType === 'cheque') {
            $('.chq-field').show();
        } else {
            $('.chq-field').hide();
        }
    }

    function toggleBiltyFields() {
        let expenseType = $('#expense_type').val();
        if (expenseType === 'bility') {
            $('.bilty-fields').show();
        } else {
            $('.bilty-fields').hide();
        }
    }
});
  

function calculateRate() {
    const expenseType = document.getElementById('expense_type')?.value || '';
    const amount = parseFloat(document.getElementById('amount').value) || 0;
    const carton = parseFloat(document.getElementById('carton')?.value) || 0;

    if (expenseType === 'bility' && carton > 0) {
        const rate = (amount / carton).toFixed(2);
        document.getElementById('rate').value = rate;
    } else {
        document.getElementById('rate').value = '';
    }
}

document.addEventListener('DOMContentLoaded', function () {
    const amountInput = document.getElementById('amount');
    const cartonInput = document.getElementById('carton');
    const expenseTypeSelect = document.getElementById('expense_type');

    if (amountInput && cartonInput) {
        amountInput.addEventListener('input', calculateRate);
        cartonInput.addEventListener('input', calculateRate);
    }

    if (expenseTypeSelect) {
        expenseTypeSelect.addEventListener('change', function () {
            calculateRate();

            const isBility = this.value === 'bility';
            document.querySelectorAll('.bilty-fields').forEach(function (field) {
                field.style.display = isBility ? 'block' : 'none';
            });
        });

        // Trigger on load in edit mode
        calculateRate();
    }
});



</script>

</body>
</html>