<!DOCTYPE html>
<html>
<head>
  <!-- FORM CSS CODE -->
  <?php $this->load->view('comman/code_css.php'); ?>
  <!-- </copy> -->
  <?php
    // Load multi-currency helper
    $this->load->helper('multi_currency_helper');
    
    // Debug: Check what variables are available (disabled)
    // echo "<!-- Debug: quotation_id = " . (isset($quotation_id) ? $quotation_id : 'not set') . " -->";
    // echo "<!-- Debug: quotation_currency_symbol = " . (isset($quotation_currency_symbol) ? $quotation_currency_symbol : 'not set') . " -->";
    // echo "<!-- Debug: currency_symbol = " . (isset($currency_symbol) ? $currency_symbol : 'not set') . " -->";
    
    // Get currency information - use transaction currency if editing, otherwise base currency
    if (isset($quotation_id) && !empty($quotation_currency_symbol)) {
      // Editing existing quotation - use transaction's currency
      $currency_symbol = $quotation_currency_symbol;
      $currency_code = isset($quotation_currency_code) ? $quotation_currency_code : 'USD';
      $transaction_currency_id = isset($quotation_currency_id) ? $quotation_currency_id : 1;
    } elseif (!empty($quotation_currency_symbol)) {
      // New quotation with currency set by controller
      $currency_symbol = $quotation_currency_symbol;
      $currency_code = isset($quotation_currency_code) ? $quotation_currency_code : 'USD';
      $transaction_currency_id = isset($quotation_currency_id) ? $quotation_currency_id : 1;
    } else {
      // Adding new quotation - try multiple methods to get currency
      $currency_symbol = '';
      $currency_code = 'USD';
      $transaction_currency_id = 1;
      
      // Method 1: Try base currency function
      $base_currency = get_base_currency();
      if ($base_currency && !empty($base_currency->symbol)) {
        $currency_symbol = $base_currency->symbol;
        $currency_code = $base_currency->currency_code;
        $transaction_currency_id = $base_currency->id;
      } else {
        // Method 2: Try session currency
        $session_currency = $this->session->userdata('currency');
        if (!empty($session_currency)) {
          $currency_symbol = $session_currency;
          $currency_code = $this->session->userdata('currency_code') ?: 'USD';
        } else {
          // Method 3: Direct database query
          $store_id = get_current_store_id();
          $currency_query = $this->db->query("SELECT c.symbol, c.currency_code, c.id FROM db_currency c, db_store s WHERE s.currency_id = c.id AND s.id = '$store_id' AND c.status = 1");
          if ($currency_query->num_rows() > 0) {
            $currency_row = $currency_query->row();
            $currency_symbol = $currency_row->symbol;
            $currency_code = $currency_row->currency_code;
            $transaction_currency_id = $currency_row->id;
          } else {
            // Method 4: Get first available currency from database
            $currency_query = $this->db->query("SELECT symbol, currency_code, id FROM db_currency WHERE status = 1 ORDER BY id LIMIT 1");
            if ($currency_query->num_rows() > 0) {
              $currency_row = $currency_query->row();
              $currency_symbol = $currency_row->symbol;
              $currency_code = $currency_row->currency_code;
              $transaction_currency_id = $currency_row->id;
            } else {
              // Last resort - leave empty to trigger error handling
              $currency_symbol = '';
              $currency_code = '';
              $transaction_currency_id = 0;
            }
          }
        }
      }
    }
    
    // Final validation - if no currency found, show error message
    if (empty($currency_symbol)) {
      // This should not happen if currency is properly configured
      $currency_symbol = '[CURRENCY NOT SET]';
      $currency_code = 'ERROR';
      $transaction_currency_id = 0;
    }
    
    // Debug: Check what variables are available (temporarily enabled for debugging)
    echo "<!-- Debug: quotation_id = " . (isset($quotation_id) ? $quotation_id : 'not set') . " -->";
    echo "<!-- Debug: quotation_currency_symbol = " . (isset($quotation_currency_symbol) ? $quotation_currency_symbol : 'not set') . " -->";
    echo "<!-- Debug: currency_symbol = " . (isset($currency_symbol) ? $currency_symbol : 'not set') . " -->";
    echo "<!-- Debug: session currency = " . $this->session->userdata('currency') . " -->";
    echo "<!-- Debug: store_id = " . get_current_store_id() . " -->";
    echo "<!-- Debug: base_currency result = " . (get_base_currency() ? 'found' : 'not found') . " -->";
  ?>
  <style type="text/css">
    table.table-bordered > thead > tr > th {
      /* border:1px solid black;*/
      text-align: center;
    }
    .table > tbody > tr > td,
    .table > tbody > tr > th,
    .table > tfoot > tr > td,
    .table > tfoot > tr > th,
    .table > thead > tr > td,
    .table > thead > tr > th {
      padding-left: 2px;
      padding-right: 2px;
    }
    
    /* Enterprise Alert Styles */
    .enterprise-alert {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        padding: 15px 20px;
        border-radius: 5px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        max-width: 400px;
        font-size: 14px;
        line-height: 1.4;
    }
    
    .enterprise-alert.warning {
        background: #fff3cd;
        border: 1px solid #ffeaa7;
        color: #856404;
    }
    
    .enterprise-alert.success {
        background: #d4edda;
        border: 1px solid #c3e6cb;
        color: #155724;
    }
    
    .enterprise-alert.error {
        background: #f8d7da;
        border: 1px solid #f5c6cb;
        color: #721c24;
    }
    
    .enterprise-alert i {
        margin-right: 8px;
        font-size: 16px;
    }
    
    .enterprise-alert .btn {
        margin-top: 10px;
        font-size: 12px;
        padding: 5px 10px;
    }
  </style>
</head>

<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">

  <?php $this->load->view('sidebar'); ?>

  <?php
    $CI =& get_instance();
    if (!isset($quotation_id)) {
      $customer_id = $quotation_date = $quotation_status = $warehouse_id =
      $reference_no = $other_charges_input = $other_charges_tax_id = $store_id =
      $discount_type = $quotation_note = '';
      $quotation_date = show_date(date("d-m-Y"));
      $expire_date = '';
      $discount_input = 0;
      $discount_input = ($discount_input==0) ? '' : $discount_input;
    } else {
      // Load quotation data - use controller data if available, otherwise load from database
      if (isset($quotation_data)) {
        // Use data from controller (includes currency information)
        $customer_id = $quotation_data->customer_id;
        $quotation_date = show_date($quotation_data->quotation_date);
        $expire_date = (!empty($quotation_data->expire_date)) ? show_date($quotation_data->expire_date) : '';
        $quotation_status = $quotation_data->quotation_status;
        $warehouse_id = $quotation_data->warehouse_id;
        $reference_no = $quotation_data->reference_no;
        $discount_input = $quotation_data->discount_to_all_input;
        $discount_type = $quotation_data->discount_to_all_type;
        $other_charges_input = $quotation_data->other_charges_input;
        $other_charges_tax_id = $quotation_data->other_charges_tax_id;
        $quotation_note = $quotation_data->quotation_note;
        $store_id = $quotation_data->store_id;
      } else {
        // Fallback to database query
        $q2 = $this->db->query("select * from db_quotation where id=$quotation_id");
        $customer_id = $q2->row()->customer_id;
        $quotation_date = show_date($q2->row()->quotation_date);
        $expire_date = (!empty($q2->row()->expire_date)) ? show_date($q2->row()->expire_date) : '';
        $quotation_status = $q2->row()->quotation_status;
        $warehouse_id = $q2->row()->warehouse_id;
        $reference_no = $q2->row()->reference_no;
        $discount_input = $q2->row()->discount_to_all_input;
        $discount_type = $q2->row()->discount_to_all_type;
        $other_charges_input = $q2->row()->other_charges_input;
        $other_charges_tax_id = $q2->row()->other_charges_tax_id;
        $quotation_note = $q2->row()->quotation_note;
        $store_id = $q2->row()->store_id;
      }

      $items_count = $this->db->query("select count(*) as items_count from db_quotationitems where quotation_id=$quotation_id")->row()->items_count;
    }
  ?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- **********************MODALS***************** -->
    <?php $this->load->view('modals/modal_customer'); ?>
    <?php $this->load->view('modals/modal_item'); ?>
    <?php $this->load->view('modals/modal_item_or_service'); ?>
    <?php /*$this->load->view('modals/modal_service');*/ ?>
    <!-- **********************MODALS END***************** -->

    <!-- Content Header (Page header) -->
    <section class="content-header">
      <h1>
        <?=$page_title;?>
        <small>Add/Update Quotation</small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
        <li><a href="<?php echo $base_url; ?>quotation"><?= $this->lang->line('quotation_list'); ?></a></li>
        <li><a href="<?php echo $base_url; ?>quotation/add">New Quotation</a></li>
        <li class="active"><?=$page_title;?></li>
      </ol>
    </section>

    <!-- Main content -->
    <section class="content">
      <div class="row">
        <!-- ********** ALERT MESSAGE START******* -->
        <?php $this->load->view('comman/code_flashdata'); ?>
        <?php $this->load->view('modals/modal_sales_item'); ?>
        <!-- ********** ALERT MESSAGE END******* -->

        <div class="col-md-12">
          <div class="box box-primary">

            <!-- form start -->
            <?= form_open('#', array('class' => 'form-horizontal', 'id' => 'quotation-form', 'enctype'=>'multipart/form-data', 'method'=>'POST')); ?>
              <input type="hidden" id="base_url" value="<?php echo $base_url; ?>">
              <input type="hidden" value="1" id="hidden_rowcount" name="hidden_rowcount">
              <input type="hidden" value="0" id="hidden_update_rowid" name="hidden_update_rowid">
              <input type="hidden" id="is_editing" value="<?= isset($quotation_id) ? '1' : '0'; ?>">
              <input type="hidden" id="transaction_currency_id" value="<?= $transaction_currency_id; ?>">
              <!-- values used by JS calculations -->
              <input type="hidden" id="hidden_total_amt" name="hidden_total_amt" value="0">
              <input type="hidden" id="hidden_discount_to_all_amt" name="hidden_discount_to_all_amt" value="0">

              <div class="box-body">
                <!-- Store Code -->
                <?php
                  // If store module is on + admin, you might show selector; default to current store
                  echo "<input type='hidden' name='store_id' id='store_id' value='".get_current_store_id()."'>";
                ?>
                <!-- Warehouse Code -->
                <?php
                  if (warehouse_module() && warehouse_count() > 1) {
                    $this->load->view('warehouse/warehouse_code', array(
                      'show_warehouse_select_box'=>true,
                      'warehouse_id'=>$warehouse_id,
                      'div_length'=>'col-sm-3',
                      'show_select_option'=>false
                    ));
                  } else {
                    echo "<input type='hidden' name='warehouse_id' id='warehouse_id' value='".get_store_warehouse_id()."'>";
                  }
                ?>

                <div class="form-group">
                  <label for="customer_id" class="col-sm-2 control-label">
                    <?= $this->lang->line('customer_name'); ?>
                    <label class="text-danger">*</label>
                  </label>
                  <div class="col-sm-3">
                    <div class="input-group">
                      <select class="form-control select2" id="customer_id" name="customer_id" style="width: 100%;"></select>
                      <span class="input-group-addon pointer" data-toggle="modal" data-target="#customer-modal" title="New Customer?">
                        <i class="fa fa-user-plus text-primary fa-lg"></i>
                      </span>
                    </div>
                    <span id="customer_id_msg" style="display:none" class="text-danger"></span>
                    <label><?= $this->lang->line('previous_due'); ?> :
                      <label class="customer_previous_due text-red" style="font-size: 18px;">0.00</label>
                    </label>
                    <div id="customer_currency_info" style="display: none; margin-top: 5px;">
                      <small class="text-info">Customer Currency: <span id="customer_currency_display"></span></small>
                    </div>
                  </div>

                  <label for="quotation_date" class="col-sm-2 control-label">
                    <?= $this->lang->line('quotation_date'); ?> <label class="text-danger">*</label>
                  </label>
                  <div class="col-sm-3">
                    <div class="input-group date">
                      <div class="input-group-addon"><i class="fa fa-calendar"></i></div>
                      <input type="text" class="form-control pull-right datepicker" id="quotation_date" name="quotation_date" readonly onkeyup="shift_cursor(event,'quotation_status')" value="<?= $quotation_date; ?>">
                    </div>
                    <span id="quotation_date_msg" style="display:none" class="text-danger"></span>
                  </div>
                </div>

                <div class="form-group hide">
                  <label for="quotation_status" class="col-sm-2 control-label">
                    <?= $this->lang->line('status'); ?> <label class="text-danger">*</label>
                  </label>
                  <div class="col-sm-3">
                    <select class="form-control select2" id="quotation_status" name="quotation_status" style="width: 100%;" onkeyup="shift_cursor(event,'mobile')">
                      <?php $pending_select = ($quotation_status=='Quotation') ? 'selected' : ''; ?>
                      <option <?= $pending_select; ?> value="Quotation">Quotation</option>
                    </select>
                    <span id="quotation_status_msg" style="display:none" class="text-danger"></span>
                  </div>
                </div>

                <div class="form-group">
                  <label for="expire_date" class="col-sm-2 control-label"><?= $this->lang->line('expire_date'); ?></label>
                  <div class="col-sm-3">
                    <div class="input-group date">
                      <div class="input-group-addon"><i class="fa fa-calendar"></i></div>
                      <input type="text" class="form-control pull-right datepicker" id="expire_date" name="expire_date" onkeyup="shift_cursor(event,'expire_status')" value="<?= $expire_date; ?>">
                    </div>
                    <span id="expire_date_msg" style="display:none" class="text-danger"></span>
                  </div>

                  <label for="reference_no" class="col-sm-2 control-label"><?= $this->lang->line('reference_no'); ?></label>
                  <div class="col-sm-3">
                    <input type="text" value="<?php echo $reference_no; ?>" class="form-control" id="reference_no" name="reference_no" placeholder="">
                    <span id="reference_no_msg" style="display:none" class="text-danger"></span>
                  </div>
                </div>

              </div>
              <!-- /.box-body -->

              <div class="row">
                <div class="col-md-12">
                  <div class="col-md-12">
                    <div class="box">
                      <div class="box-info">
                        <div class="box-header">
                          <div class="col-md-8 col-md-offset-2 text-center">
                            <div class="input-group">
                              <span class="input-group-addon" title="Select Items"><i class="fa fa-barcode"></i></span>
                              <input type="text" class="form-control" placeholder="Item name/Barcode/Itemcode" autofocus id="item_search">
                              <span class="input-group-addon pointer text-green show_item_service" title="Click to Add New Item or Service"><i class="fa fa-plus"></i></span>
                            </div>
                          </div>
                        </div>

                        <div class="box-body">
                          <div class="table-responsive" style="width: 100%">
                            <table class="table table-hover table-bordered" style="width:100%" id="quotation_table">
                              <thead class="custom_thead">
                                <tr class="bg-primary">
                                  <th rowspan="2" style="width:15%"><?= $this->lang->line('item_name'); ?></th>
                                  <th rowspan="2" style="width:10%;min-width:180px;"><?= $this->lang->line('quantity'); ?></th>
                                  <th rowspan="2" style="width:10%"><?= $this->lang->line('unit_price'); ?> (<span id="unit_price_currency_symbol"><?= $currency_symbol; ?></span>)</th>
                                  <th rowspan="2" style="width:10%"><?= $this->lang->line('discount'); ?>(<span id="discount_currency_symbol"><?= $currency_symbol; ?></span>)</th>
                                  <th rowspan="2" style="width:10%"><?= $this->lang->line('tax_amount'); ?></th>
                                  <th rowspan="2" style="width:5%"><?= $this->lang->line('tax'); ?></th>
                                  <th rowspan="2" style="width:7.5%"><?= $this->lang->line('total_amount'); ?></th>
                                  <th rowspan="2" style="width:7.5%"><?= $this->lang->line('action'); ?></th>
                                </tr>
                              </thead>
                              <tbody>
                                <!-- Rows append here via JS -->
                              </tbody>
                            </table>
                          </div>
                        </div>

                      </div>
                    </div>

                  </div>
                </div>

                <div class="col-md-6">
                  <div class="row">
                    <div class="col-md-12">
                      <div class="form-group">
                        <label class="col-sm-4 control-label"><?= $this->lang->line('quantity'); ?></label>
                        <div class="col-sm-4">
                          <label class="control-label total_quantity text-success" style="font-size:15pt;">0</label>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="row">
                    <div class="col-md-12">
                      <div class="form-group">
                        <label for="other_charges_input" class="col-sm-4 control-label"><?= $this->lang->line('other_charges'); ?></label>
                        <div class="col-sm-4">
                          <input type="text" class="form-control text-right only_currency" id="other_charges_input" name="other_charges_input" onkeyup="final_total();" value="<?php echo $other_charges_input; ?>">
                        </div>
                        <div class="col-sm-4">
                          <select class="form-control" id="other_charges_tax_id" name="other_charges_tax_id" onchange="final_total();" style="width: 100%;">
                            <?= get_tax_select_list($other_charges_tax_id, get_current_store_id()); ?>
                          </select>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div class="row">
                    <div class="col-md-12">
                      <div class="form-group">
                        <label for="discount_to_all_input" class="col-sm-4 control-label"><?= $this->lang->line('discount_on_all'); ?></label>
                        <div class="col-sm-4">
                          <input type="text" class="form-control text-right only_currency" id="discount_to_all_input" name="discount_to_all_input" onkeyup="enable_or_disable_item_discount();" value="<?php echo $discount_input; ?>">
                        </div>
                        <div class="col-sm-4">
                          <select class="form-control" onchange="final_total();" id="discount_to_all_type" name="discount_to_all_type">
                            <option value="in_percentage">Per%</option>
                            <option value="in_fixed">Fixed</option>
                          </select>
                        </div>
                        <script type="text/javascript">
                          <?php if ($discount_type != '') { ?>
                            document.addEventListener('DOMContentLoaded', function() {
                              document.getElementById('discount_to_all_type').value = '<?= $discount_type; ?>';
                            });
                          <?php } ?>
                        </script>
                      </div>
                    </div>
                  </div>

                  <div class="row">
                    <div class="col-md-12">
                      <div class="form-group">
                        <label for="quotation_note" class="col-sm-4 control-label"><?= $this->lang->line('note'); ?></label>
                        <div class="col-sm-8">
                          <textarea class="form-control text-left" id="quotation_note" name="quotation_note"><?= $quotation_note; ?></textarea>
                          <span id="quotation_note_msg" style="display:none" class="text-danger"></span>
                        </div>
                      </div>
                    </div>
                  </div>

                </div>

                <div class="col-md-6">
                  <div class="row">
                    <div class="col-md-12">
                      <div class="form-group">

                        <table class="col-md-9">
                          <tr>
                            <th class="text-right" style="font-size:17px;"><?= $this->lang->line('subtotal'); ?></th>
                            <th class="text-right" style="padding-left:10%;font-size:17px;">
                              <h4><b><span id="subtotal_currency_symbol"><?= $currency_symbol; ?></span> <span id="subtotal_amt" name="subtotal_amt">0.00</span></b></h4>
                            </th>
                          </tr>
                          <tr>
                            <th class="text-right" style="font-size:17px;"><?= $this->lang->line('other_charges'); ?></th>
                            <th class="text-right" style="padding-left:10%;font-size:17px;">
                              <h4><b><span id="other_charges_currency_symbol"><?= $currency_symbol; ?></span> <span id="other_charges_amt" name="other_charges_amt">0.00</span></b></h4>
                            </th>
                          </tr>
                          <tr>
                            <th class="text-right" style="font-size:17px;"><?= $this->lang->line('discount_on_all'); ?></th>
                            <th class="text-right" style="padding-left:10%;font-size:17px;">
                              <h4><b><span id="discount_to_all_currency_symbol"><?= $currency_symbol; ?></span> <span id="discount_to_all_amt" name="discount_to_all_amt">0.00</span></b></h4>
                            </th>
                          </tr>

                          <!-- Optional overall tax display (was referenced in JS) -->
                          <tr>
                            <th class="text-right" style="font-size:17px;"><?= $this->lang->line('tax_amount'); ?></th>
                            <th class="text-right" style="padding-left:10%;font-size:17px;">
                              <h4><b><span id="tax_currency_symbol"><?= $currency_symbol; ?></span> <span id="tax_amt" name="tax_amt">0.00</span></b></h4>
                            </th>
                          </tr>

                          <tr style="<?= (!is_enabled_round_off()) ? 'display: none;' : '';?>">
                            <th class="text-right" style="font-size:17px;">
                              <?= $this->lang->line('round_off'); ?>
                              <i class="hover-q" data-container="body" data-toggle="popover" data-placement="top" data-content="Go to Site Settings-> Site -> Disable the Round Off(Checkbox)." data-html="true" data-trigger="hover" title="Do you wants to Disable Round Off ?">
                                <i class="fa fa-info-circle text-maroon text-black hover-q"></i>
                              </i>
                            </th>
                            <th class="text-right" style="padding-left:10%;font-size:17px;">
                              <h4><b><span id="round_off_currency_symbol"><?= $currency_symbol; ?></span> <span id="round_off_amt" name="tot_round_off_amt">0.00</span></b></h4>
                            </th>
                          </tr>
                          <tr>
                            <th class="text-right" style="font-size:17px;"><?= $this->lang->line('grand_total'); ?></th>
                            <th class="text-right" style="padding-left:10%;font-size:17px;">
                              <h4><b><span id="grand_total_currency_symbol"><?= $currency_symbol; ?></span> <span id="total_amt" name="total_amt">0.00</span></b></h4>
                            </th>
                          </tr>
                        </table>

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

                <!-- SMS Sender while saving -->
                <?php
                  $send_sms_checkbox = 'disabled';
                  if ($CI->is_sms_enabled()) {
                    if (!isset($quotation_id)) {
                      $send_sms_checkbox = 'checked';
                    } else {
                      $send_sms_checkbox = '';
                    }
                  }
                ?>

                <div class="col-xs-12">
                  <div class="col-sm-12">
                    <div class="box-body">
                      <div class="col-md-12">
                        <div class="checkbox icheck">
                          <label>
                            <input type="checkbox" <?=$send_sms_checkbox;?> class="form-control" id="send_sms" name="send_sms">
                            <label for="send_sms" class="control-label"><?= $this->lang->line('send_sms_to_customer'); ?>
                              <i class="hover-q" data-container="body" data-toggle="popover" data-placement="top" data-content="If checkbox is Disabled! You need to enable it from SMS -> SMS API <br><b>Note:<i>Walk-in Customer will not receive SMS!</i></b>" data-html="true" data-trigger="hover" title="Do you wants to send SMS ?">
                                <i class="fa fa-info-circle text-maroon text-black hover-q"></i>
                              </i>
                            </label>
                          </label>
                        </div>
                      </div><!-- col-md-12 -->
                    </div>
                  </div>
                </div>

              </div><!-- /.row -->

              <div class="box-footer col-sm-12">
                <center>
                  <?php
                    if (isset($quotation_id)) {
                      $btn_id = 'update';
                      $btn_name = "Update";
                      echo '<input type="hidden" name="quotation_id" id="quotation_id" value="'.$quotation_id.'"/>';
                    } else {
                      $btn_id = 'save';
                      $btn_name = "Save";
                    }
                  ?>
                  <div class="col-md-3 col-md-offset-3">
                    <button type="button" id="<?php echo $btn_id; ?>" class="btn btn-block btn-success payments_modal" title="Save Data"><?php echo $btn_name; ?></button>
                  </div>
                  <div class="col-sm-3">
                    <a href="<?= base_url() ?>dashboard">
                      <button type="button" class="btn btn-block btn-warning" title="Go Dashboard">Close</button>
                    </a>
                  </div>
                </center>
              </div>

            <?= form_close(); ?>
            <!-- form end -->

          </div>
        </div>

      </div><!-- /.row -->
    </section><!-- /.content -->

  </div><!-- /.content-wrapper -->

  <?php $this->load->view('footer'); ?>
  <!-- SOUND CODE -->
  <?php $this->load->view('comman/code_js_sound'); ?>
  <!-- GENERAL CODE -->
  <?php $this->load->view('comman/code_js'); ?>

  <script src="<?php echo $theme_link; ?>js/modals.js"></script>
  <script src="<?php echo $theme_link; ?>js/modals/modal_item.js"></script>

  <div class="control-sidebar-bg"></div>
</div><!-- ./wrapper -->

<script type="text/javascript">
  // Removed walk_in_customer_name to prevent auto-loading issues
</script>

<script src="<?php echo $theme_link; ?>js/quotation/quotation.js"></script>
<script src="<?php echo $theme_link; ?>js/ajaxselect/customer_select_ajax.js"></script>

<script>
  //Customer Selection Box Search
  function getCustomerSelectionId() { return '#customer_id'; }

  $(document).ready(function () {
    // Show consistent currency symbols in headers (already server-rendered, this is a safeguard)
    var currencySymbol = <?= json_encode($currency_symbol); ?>;
    $('#unit_price_currency_symbol, #discount_currency_symbol, #subtotal_currency_symbol, #other_charges_currency_symbol, #discount_to_all_currency_symbol, #tax_currency_symbol, #round_off_currency_symbol, #grand_total_currency_symbol').text(currencySymbol);

    // Load customers for the current store
    var store_id = $("#store_id").val();
    var customer_id = "<?= (!empty($customer_id)) ? $customer_id : ''; ?>";
    
    if (store_id) {
      $.post(base_url + "quotation/get_customers_select_list", {store_id:store_id}, function(result){
        $("#customer_id").html('').append(result).select2();
        
        // If editing and customer_id is set, select the correct customer
        if (customer_id !== '') {
          $("#customer_id").val(customer_id).trigger('change');
          // Update currency symbols for existing quotation
          var quotationCurrencySymbol = '<?= isset($quotation_currency_symbol) ? $quotation_currency_symbol : get_base_currency()->symbol ?>';
          updateCurrencySymbols(quotationCurrencySymbol);
        }
      });
    }

    // Initialize UI
    $(".select2").select2();
    $('.datepicker').datepicker({ autoclose:true, format:'dd-mm-yyyy', todayHighlight:true });
  });

  function set_previous_due(previous_due, tot_advance){
    $(".customer_previous_due").html(previous_due);
  }

  var base_url = $("#base_url").val();

  $("#store_id").on("change", function(){
    var store_id = $("#store_id").val();
    $.post(base_url + "quotation/get_customers_select_list", {store_id:store_id}, function(result){
      $("#customer_id").html('').append(result).select2();
      $("#quotation_table > tbody").empty();
      calculate_tax();
    });
    $.post(base_url + "quotation/get_tax_select_list", {store_id:store_id}, function(result){
      $("#other_charges_tax_id").html('').append(result).select2();
      calculate_tax();
    });
  });

  // Customer change event for exchange rate check
  $("#customer_id").on("change select2:select", function(){
    checkCustomerCurrencyExchangeRate();
  });

  // Global flag to track exchange rate validation
  var exchangeRateValid = true;
  var exchangeRateCheckInProgress = false;

  // Function to check exchange rate between currencies
  function checkExchangeRate(from_currency_id, to_currency_id, from_currency_name, from_currency_code, to_currency_name, to_currency_code) {
      if (!from_currency_id || !to_currency_id || from_currency_id == to_currency_id) {
          exchangeRateValid = true;
          return; // No need to check if same currency or missing data
      }

      var base_url = $("#base_url").val();
      exchangeRateCheckInProgress = true;
      
      $.ajax({
          url: base_url + 'exchange_rates/check_exchange_rate',
          type: 'POST',
          data: { 
              from_currency_id: from_currency_id,
              to_currency_id: to_currency_id
          },
          dataType: 'json',
          success: function(response) {
              exchangeRateCheckInProgress = false;
              
              if (!response || !response.exists) {
                  exchangeRateValid = false;
                  // Show enterprise alert like in sales
                  showEnterpriseAlert(
                      'Rate missing, please add exchange rate for this currency conversion.',
                      'warning'
                  );
              } else {
                  exchangeRateValid = true;
                  // Rate exists, no alert needed
              }
          },
          error: function(xhr, status, error) {
              exchangeRateCheckInProgress = false;
              exchangeRateValid = false;
              // Don't show alert on error - let the success handler handle it
          }
      });
  }

  // Enterprise Alert System
  function showEnterpriseAlert(message, type) {
      // Remove any existing alerts
      $('.enterprise-alert').remove();
      
      var alertClass = 'warning';
      if (type === 'success') alertClass = 'success';
      if (type === 'error') alertClass = 'error';
      
      var alertHtml = '<div class="enterprise-alert ' + alertClass + '">' +
          '<i class="fa fa-exclamation-triangle"></i> ' + message +
          '<br><br>' +
          '<a href="' + $("#base_url").val() + 'exchange_rates" class="btn btn-sm btn-warning" style="margin-top: 8px;">' +
          '<i class="fa fa-plus"></i> Add Exchange Rate</a>' +
          '</div>';
      
      $('body').append(alertHtml);
      
      // Auto remove after 8 seconds (longer to allow user to click button)
      setTimeout(function() {
          $('.enterprise-alert').fadeOut(300, function() {
              $(this).remove();
          });
      }, 8000);
  }

  // Function to check customer currency exchange rate
  function checkCustomerCurrencyExchangeRate() {
      var customer_id = $("#customer_id").val();
      var base_currency_id = '<?= get_base_currency()->id ?>';
      
      if (!customer_id) {
          // Reset to base currency when no customer selected
          var baseCurrencySymbol = '<?= get_base_currency()->symbol ?>';
          updateCurrencySymbols(baseCurrencySymbol);
          $('#customer_currency_info').hide();
          return;
      }

      // Get customer currency via AJAX
      $.ajax({
          url: base_url + 'quotation/get_customer_currency',
          type: 'POST',
          data: { customer_id: customer_id },
          dataType: 'json',
          success: function(response) {
              if (response && response.status) {
                  // Update currency symbols to customer's currency
                  updateCurrencySymbols(response.currency_symbol);
                  
                  // Show customer currency info
                  if (response.customer_currency_id && response.customer_currency_id != base_currency_id) {
                      $('#customer_currency_display').text(response.currency_name + ' (' + response.currency_code + ')');
                      $('#customer_currency_info').show();
                      
                      // Check if exchange rate exists in database
                      checkExchangeRate(
                          response.customer_currency_id, 
                          response.base_currency_id,
                          response.customer_currency_name,
                          response.customer_currency_code,
                          response.base_currency_name,
                          response.base_currency_code
                      );
                  } else {
                      $('#customer_currency_info').hide();
                  }
              }
          },
          error: function() {
              console.log('Error getting customer currency');
              // Reset to base currency on error
              var baseCurrencySymbol = '<?= get_base_currency()->symbol ?>';
              updateCurrencySymbols(baseCurrencySymbol);
              $('#customer_currency_info').hide();
          }
      });
  }
  
  // Function to update all currency symbols in the form
  function updateCurrencySymbols(symbol) {
      $('#unit_price_currency_symbol, #discount_currency_symbol, #subtotal_currency_symbol, #other_charges_currency_symbol, #discount_to_all_currency_symbol, #tax_currency_symbol, #round_off_currency_symbol, #grand_total_currency_symbol').text(symbol);
  }
  
  // Function to update exchange rate and recalculate amounts
  function updateExchangeRate() {
      var exchangeRate = parseFloat($('#exchange_rate').val()) || 1.0;
      $('#exchange_rate_value').text(exchangeRate.toFixed(4));
      
      // Recalculate base currency amounts
      calculateBaseCurrencyAmounts();
  }
  
  // Function to calculate base currency amounts
  function calculateBaseCurrencyAmounts() {
      var exchangeRate = parseFloat($('#exchange_rate').val()) || 1.0;
      var customerCurrencyTotal = parseFloat($('#total_amt').text()) || 0;
      var baseCurrencyAmount = customerCurrencyTotal / exchangeRate;
      
      $('#base_currency_amount_display').text(baseCurrencyAmount.toFixed(2));
  }
  
  // Form submission blocking for exchange rate validation
  $(document).on('submit', '#quotation-form', function(e) {
      if (!exchangeRateValid) {
          e.preventDefault();
          showEnterpriseAlert(
              'Please add the required exchange rate before proceeding with the transaction.',
              'error'
          );
          return false;
      }
  });
  
  // Block save button clicks when exchange rate is invalid
  $(document).on('click', '#save, #update', function(e) {
      if (!exchangeRateValid) {
          e.preventDefault();
          showEnterpriseAlert(
              'Please add the required exchange rate before proceeding with the transaction.',
              'error'
          );
          return false;
      }
  });

  /*Warehouse*/
  $("#warehouse_id").on("change", function(){
    $("#quotation_table > tbody").empty();
    final_total();
  });
  /*Warehouse end*/

  $(".close_btn").on("click", function(){
    if (confirm('Are you sure you want to navigate away from this page?')){
      window.location = '<?php echo $base_url; ?>dashboard';
    }
  });

  /* ---------- CALCULATE TAX -------------*/
  function calculate_tax(i){ //i=Row
    if (typeof i === 'undefined' || i === null) return;
    set_tax_value(i);

    //Find the Tax type and Tax amount
    var tax_type   = $("#tr_tax_type_"+i).val() || 'Exclusive';
    var tax_amount = parseFloat($("#td_data_"+i+"_11").val()) || 0;

    var qty = parseFloat($("#td_data_"+i+"_3").val()) || 0;
    var quotation_price = parseFloat($("#td_data_"+i+"_10").val()) || 0;
    $("#td_data_"+i+"_4").val(quotation_price);

    /*Discount*/
    var discount_amt = parseFloat($("#td_data_"+i+"_8").val());
    discount_amt = isNaN(discount_amt) ? 0 : discount_amt;

    var amt = qty * quotation_price; //Taxable
    var total_amt = amt - discount_amt;
    total_amt = (tax_type === 'Inclusive') ? total_amt : (parseFloat(total_amt) + parseFloat(tax_amount));

    //Set Unit cost
    $("#td_data_"+i+"_9").val('').val(to_Fixed(total_amt));
    final_total();
  }
  /* ---------- CALCULATE TAX END -------------*/

  /* ---------- Final Description of amount ------------*/
  function final_total(){
    var rowcount = parseInt($("#hidden_rowcount").val()) || 0;
    var subtotal = 0;

    var other_charges_per_amt = 0;
    var other_charges_total_amt = 0;
    var taxable = 0;

    var other_charges_tax_id = 0, other_charges_input = 0;

    if ($("#other_charges_input").val() != null && $("#other_charges_input").val() !== ''){
      other_charges_tax_id = parseFloat($('option:selected', '#other_charges_tax_id').attr('data-tax')) || 0;
      other_charges_input  = parseFloat($("#other_charges_input").val()) || 0;

      if (other_charges_tax_id > 0){
        other_charges_per_amt = (other_charges_tax_id * other_charges_input) / 100;
      }

      taxable = parseFloat(other_charges_per_amt) + parseFloat(other_charges_input); //Other charges input
      other_charges_total_amt = parseFloat(other_charges_per_amt) + parseFloat(other_charges_input);
    }

    var tax_amt = 0;
    var actual_taxable = 0;
    var total_quantity = 0;

    for (var i = 1; i <= rowcount; i++){
      if (document.getElementById("td_data_"+i+"_3")){
        if ($("#td_data_"+i+"_3").val() != null && $("#td_data_"+i+"_3").val() !== ''){
          actual_taxable += (parseFloat($("#td_data_"+i+"_13").val()) || 0) * (parseFloat($("#td_data_"+i+"_3").val()) || 0);
          subtotal += parseFloat($("#td_data_"+i+"_9").val()) || 0;
          if ((parseFloat($("#td_data_"+i+"_7").val()) || 0) >= 0){
            tax_amt += parseFloat($("#td_data_"+i+"_7").val()) || 0;
          }
          total_quantity += parseFloat($("#td_data_"+i+"_3").val()) || 0;
        }
      }
    }

    //Show total Quotation Quantities
    $(".total_quantity").html(format_qty(total_quantity));

    if ((subtotal != null || subtotal !== '') && (subtotal != 0)){
      $("#subtotal_amt").html(to_Fixed(subtotal));
      $("#other_charges_amt").html(to_Fixed(other_charges_total_amt));

      taxable = taxable + subtotal;

      var discount_input = parseFloat($("#discount_to_all_input").val());
      discount_input = isNaN(discount_input) ? 0 : discount_input;

      var discount = 0;
      if (discount_input > 0){
        var discount_type = $("#discount_to_all_type").val();
        if (discount_type == 'in_fixed'){
          taxable -= discount_input;
          discount = discount_input;
        }
        else if (discount_type == 'in_percentage'){
          discount = (taxable * discount_input) / 100;
          taxable -= discount;
        }
      }
      discount = parseFloat(to_Fixed(discount));

      $("#discount_to_all_amt").html(discount);
      $("#hidden_discount_to_all_amt").val(discount);

      // If you want to show total tax (accumulated)
      $("#tax_amt").html(to_Fixed(tax_amt));

      var subtotal_round = round_off(taxable); // custom defined in included JS
      var subtotal_diff = subtotal_round - taxable;

      $("#round_off_amt").html(to_Fixed(subtotal_diff));
      $("#total_amt").html(to_Fixed(subtotal_round));
      $("#hidden_total_amt").val(to_Fixed(subtotal_round));
    } else {
      $("#subtotal_amt").html('0.00');
      $("#tax_amt").html('0.00');
      $("#round_off_amt").html('0.00');
      $("#total_amt").html('0.00');
      $("#hidden_total_amt").val('0.00');
      $("#discount_to_all_amt").html('0.00');
      $("#hidden_discount_to_all_amt").val('0.00');
      $("#other_charges_amt").html('0.00');
    }
    
    // Calculate base currency amounts if exchange rate is set
    calculateBaseCurrencyAmounts();
  }
  /* ---------- Final Description of amount end ------------*/

  function removerow(id){//id=Rowid
    $("#row_"+id).remove();
    final_total();
    failed.currentTime = 0; failed.play();
  }

  function enable_or_disable_item_discount(){
    var rowcount = parseInt($("#hidden_rowcount").val()) || 0;
    for (var k = 1; k <= rowcount; k++){
      if (document.getElementById("tr_item_id_"+k)){
        calculate_tax(k);
      }
    }
  }

  //Sale Items Modal Operations Start
  function show_quotation_item_modal(row_id){
    $('#sales_item').modal('toggle');
    $("#popup_tax_id").select2();

    //Find the item details
    var item_name = $("#td_data_"+row_id+"_1").html();
    var tax_type = $("#tr_tax_type_"+row_id).val();
    var tax_id = $("#tr_tax_id_"+row_id).val();
    var description = $("#description_"+row_id).val();

    /*Discount*/
    var item_discount_input = $("#item_discount_input_"+row_id).val();
    var item_discount_type = $("#item_discount_type_"+row_id).val();

    //Set to Popup
    $("#item_discount_input").val(item_discount_input);
    $("#item_discount_type").val(item_discount_type).select2();

    $("#popup_item_name").html(item_name);
    $("#popup_tax_type").val(tax_type).select2();
    $("#popup_tax_id").val(tax_id).select2();
    $("#popup_description").val(description);
    $("#popup_row_id").val(row_id);
  }

  function set_info(){
    var row_id = $("#popup_row_id").val();
    var tax_type = $("#popup_tax_type").val();
    var tax_id = $("#popup_tax_id").val();
    var description = $("#popup_description").val();
    var tax_name = ($('option:selected', "#popup_tax_id").attr('data-tax-value'));
    var tax = parseFloat($('option:selected', "#popup_tax_id").attr('data-tax')) || 0;

    /*Discount*/
    var item_discount_input = $("#item_discount_input").val();
    var item_discount_type = $("#item_discount_type").val();

    //Set it into row
    $("#item_discount_input_"+row_id).val(item_discount_input);
    $("#item_discount_type_"+row_id).val(item_discount_type);

    $("#tr_tax_type_"+row_id).val(tax_type);
    $("#tr_tax_id_"+row_id).val(tax_id);
    $("#tr_tax_value_"+row_id).val(tax);//%
    $("#description_"+row_id).val(description);
    $("#td_data_"+row_id+"_12").html(tax_name);

    calculate_tax(row_id);
    $('#sales_item').modal('toggle');
  }

  function set_tax_value(row_id){
    //get the quotation price of the item
    var tax_type = $("#tr_tax_type_"+row_id).val() || 'Exclusive';
    var tax = parseFloat($("#tr_tax_value_"+row_id).val()) || 0; //%
    var qty = parseFloat($("#td_data_"+row_id+"_3").val());
        qty = (isNaN(qty)) ? 0 : qty;
    var quotation_price = parseFloat($("#td_data_"+row_id+"_10").val());
        quotation_price = (isNaN(quotation_price)) ? 0 : quotation_price;
    quotation_price = quotation_price * qty;

    /*Discount*/
    var item_discount_type = $("#item_discount_type_"+row_id).val() || 'Fixed';
    var item_discount_input = parseFloat($("#item_discount_input_"+row_id).val());
        item_discount_input = (isNaN(item_discount_input)) ? 0 : item_discount_input;

    //Calculate discount
    var discount_amt = (item_discount_type == 'Percentage')
      ? ((quotation_price) * item_discount_input) / 100
      : (item_discount_input * qty);

    quotation_price -= parseFloat(discount_amt);

    var tax_amount = (tax_type == 'Inclusive') ? calculate_inclusive(quotation_price, tax) : calculate_exclusive(quotation_price, tax);

    $("#td_data_"+row_id+"_8").val(to_Fixed(discount_amt));
    $("#td_data_"+row_id+"_11").val(to_Fixed(tax_amount));
  }
  //Sale Items Modal Operations End
</script>

<!-- UPDATE OPERATIONS -->
<script type="text/javascript">
  <?php if (isset($quotation_id)) { ?>
    $("#store_id").attr('readonly', true);
    $(document).ready(function(){
      var base_url = '<?= base_url(); ?>';
      var quotation_id = '<?= $quotation_id; ?>';
      $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
      $.post(base_url + "quotation/return_quotation_list/" + quotation_id, {}, function(result){
        $('#quotation_table tbody').append(result);
        $("#hidden_rowcount").val(parseInt(<?= (int)$items_count; ?>) + 1);
        success.currentTime = 0; success.play();
        enable_or_disable_item_discount();
        $(".overlay").remove();
      });
    });
  <?php } ?>
</script>
<!-- UPDATE OPERATIONS end-->

<!-- Make sidebar menu highlighter/selector -->
<script>$(".<?php echo basename(__FILE__,'.php'); ?>-active-li").addClass("active");</script>

<!-- Exchange Rate Required Modal -->
<div class="modal fade" id="exchangeRateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header bg-red">
        <h4 class="modal-title">
          <i class="fa fa-exclamation-triangle"></i> Exchange Rate Required
        </h4>
      </div>
      <div class="modal-body">
        <!-- Content will be dynamically inserted here -->
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>


</body>
</html>
