<!DOCTYPE html>
<html>

<head>
<!-- TABLES CSS CODE -->
<?php include"comman/code_css.php"; ?>
<!-- iCheck -->
  <link rel="stylesheet" href="<?php echo $theme_link; ?>plugins/iCheck/square/blue.css">
  <link rel="stylesheet" href="<?= base_url('theme/css/pos.css') ?>">
  <link rel="stylesheet" href="<?= base_url('theme/css/pos_compact.css') ?>">
  <link rel="stylesheet" href="<?= base_url('theme/css/modal_compact.css') ?>">
  <style>
    .customer-due-section {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 10px;
    }
    
    .customer-due-section label {
      margin: 0;
    }
    
    #customer_action_btn {
      margin-left: 10px;
      padding: 2px 8px;
      font-size: 11px;
      border-radius: 3px;
      transition: all 0.3s ease;
    }
    
    #customer_action_btn:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0,0,0,0.2);
    }
    
    #expense_btn {
      margin-left: 5px;
      padding: 2px 8px;
      font-size: 11px;
      border-radius: 3px;
      transition: all 0.3s ease;
      background-color: #28a745;
      border-color: #28a745;
    }
    
    #expense_btn:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0,0,0,0.2);
      background-color: #218838;
      border-color: #1e7e34;
    }
    
    #summary_btn {
      margin-left: 5px;
      padding: 2px 8px;
      font-size: 11px;
      border-radius: 3px;
      transition: all 0.3s ease;
      background-color: #17a2b8;
      border-color: #17a2b8;
    }
    
    #summary_btn:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0,0,0,0.2);
      background-color: #138496;
      border-color: #117a8b;
    }
    
    #stock_adj_btn {
      margin-left: 5px;
      padding: 2px 8px;
      font-size: 11px;
      border-radius: 3px;
      transition: all 0.3s ease;
      background-color: #dc3545;
      border-color: #dc3545;
    }
    
    #stock_adj_btn:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0,0,0,0.2);
      background-color: #c82333;
      border-color: #bd2130;
    }
    
    /* Expense Modal Styling */
    #expense-modal .modal-content {
      border-radius: 8px;
    }
    
    #expense-modal .modal-header {
      background: linear-gradient(45deg, #28a745, #20c997);
      color: white;
      border-radius: 8px 8px 0 0;
    }
    
    #expense-modal .modal-header .close {
      color: white;
      opacity: 0.8;
    }
    
    #expense-modal .modal-header .close:hover {
      opacity: 1;
    }
    
    #expense-modal .form-group {
      margin-bottom: 15px;
    }
    
    #expense-modal .form-control {
      border-radius: 4px;
      border: 1px solid #ddd;
    }
    
    #expense-modal .form-control:focus {
      border-color: #28a745;
      box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
    }
    
    /* Daily Summary Modal Styling */
    #daily-summary-modal .modal-content {
      border-radius: 8px;
    }
    
    #daily-summary-modal .modal-header {
      background: linear-gradient(45deg, #17a2b8, #007bff);
      color: white;
      border-radius: 8px 8px 0 0;
    }
    
    #daily-summary-modal .modal-header .close {
      color: white;
      opacity: 0.8;
    }
    
    #daily-summary-modal .modal-header .close:hover {
      opacity: 1;
    }
    
    #daily-summary-modal .small-box {
      border-radius: 6px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      position: relative;
      overflow: hidden;
    }
    
    #daily-summary-modal .small-box .icon {
      position: absolute;
      top: 5px;
      right: 5px;
      opacity: 0.3;
    }
    
    #daily-summary-modal .box {
      border-radius: 6px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.12);
    }
    
    #daily-summary-modal .box-header {
      background: #f7f7f7;
    }
    
    #daily-summary-modal .description-block {
      padding: 10px;
    }
    
    /* Compact responsive adjustments */
    @media (max-width: 576px) {
      #daily-summary-modal .modal-dialog {
        margin: 5px;
        width: auto;
      }
      
      #daily-summary-modal .small-box .inner {
        padding: 6px !important;
      }
      
      #daily-summary-modal .small-box h4 {
        font-size: 14px !important;
      }
      
      #daily-summary-modal .small-box p {
        font-size: 10px !important;
      }
    }
    
    .customer-action-modal .list-group-item {
      border: none;
      border-bottom: 1px solid #f0f0f0;
      padding: 12px 15px;
      transition: all 0.2s ease;
    }
    
    .customer-action-modal .list-group-item:hover {
      background-color: #f8f9fa;
      color: #007bff;
      transform: translateX(5px);
    }
    
    .customer-action-modal .list-group-item i {
      width: 20px;
      margin-right: 10px;
    }
    
    /* Overall Compact Form Styling */
    .compact-section {
      margin-bottom: 0 !important;
    }

    .compact-section .row {
      margin-left: -5px;
      margin-right: -5px;
    }

    .compact-section .row [class*="col-"] {
      padding-left: 5px;
      padding-right: 5px;
    }

    /* Input Group Improvements */
    .input-group-sm .form-control,
    .input-group-sm .input-group-addon {
      padding: 4px 8px !important;
      font-size: 12px !important;
      line-height: 1.2 !important;
      height: 30px !important;
    }

    .input-group-sm .input-group-addon {
      min-width: 35px;
    }

    /* Form Control Consistent Styling */
    .form-control {
      border-radius: 3px !important;
      border: 1px solid #ddd !important;
      transition: all 0.2s ease !important;
    }

    .form-control:focus {
      border-color: #007bff !important;
      box-shadow: 0 0 0 2px rgba(0,123,255,0.1) !important;
    }

    /* Box Header and Footer Improvements */
    .box-header {
      padding: 8px 15px !important;
      border-bottom: 1px solid #e0e6ed !important;
    }

    .box-footer {
      border-top: 1px solid #e0e6ed !important;
    }

    /* Row Spacing Optimization */
    .pos-top-row,
    .pos-customer-row {
      margin-bottom: 10px !important;
    }

    /* Button Group Spacing */
    .customer-due-section {
      line-height: 1.2;
    }

    .customer-due-section > div {
      margin-top: 3px;
    }

    .customer-due-section .btn {
      margin-right: 3px !important;
      margin-bottom: 2px !important;
    }

    /* Summary Row Polish */
    .compact-summary-row {
      border-radius: 4px;
      box-shadow: 0 1px 3px rgba(0,0,0,0.1);
      background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%) !important;
    }

    .summary-item {
      padding: 10px 4px !important;
      position: relative;
    }

    .summary-item:not(:last-child)::after {
      content: '';
      position: absolute;
      right: 0;
      top: 15%;
      height: 70%;
      width: 1px;
      background: linear-gradient(to bottom, transparent, #dee2e6, transparent);
    }

    /* Modern Button Group Enhanced */
    .modern-button-group {
      gap: 6px !important;
      padding: 0 !important;
    }

    .modern-btn {
      padding: 8px 6px !important;
      min-height: 38px !important;
      border-radius: 4px !important;
      font-weight: 600 !important;
      text-transform: uppercase !important;
      letter-spacing: 0.5px !important;
      transition: all 0.2s ease !important;
    }

    .modern-btn:hover:not(.disabled) {
      transform: translateY(-1px) !important;
      box-shadow: 0 3px 8px rgba(0,0,0,0.2) !important;
    }

    /* Responsive Adjustments */
    @media (max-width: 768px) {
      .compact-section .row [class*="col-"] {
        margin-bottom: 8px;
      }
      
      .customer-due-section {
        text-align: center;
      }
      
      .modern-button-group {
        justify-content: center;
      }
    }

    .modern-messaging-options {
      border: 1px solid #e0e6ed;
      box-shadow: 0 1px 2px rgba(0,0,0,0.05);
      border-radius: 4px;
      margin: 4px 0 !important;
    }

    .modern-checkbox-group {
      position: relative;
    }

    .modern-checkbox-label {
      display: flex;
      align-items: center;
      cursor: pointer;
      margin: 0;
      padding: 2px 6px;
      border-radius: 3px;
      transition: all 0.2s ease;
      font-size: 11px;
      font-weight: 500;
      line-height: 1.2;
    }

    .modern-checkbox-label:hover {
      background-color: rgba(0,123,255,0.1);
    }

    .modern-checkbox {
      opacity: 0;
      position: absolute;
      z-index: -1;
    }

    .modern-checkmark {
      width: 14px;
      height: 14px;
      border: 2px solid #ddd;
      border-radius: 2px;
      margin-right: 6px;
      position: relative;
      background: white;
      transition: all 0.2s ease;
    }

    .modern-checkbox:checked + .modern-checkmark {
      background-color: #28a745;
      border-color: #28a745;
    }

    .modern-checkbox:checked + .modern-checkmark:after {
      content: '✓';
      position: absolute;
      left: 1px;
      top: -2px;
      color: white;
      font-size: 10px;
      font-weight: bold;
    }

    .modern-checkbox:disabled + .modern-checkmark {
      background-color: #f8f9fa;
      border-color: #e9ecef;
      opacity: 0.6;
    }

    .checkbox-text {
      color: #495057;
      white-space: nowrap;
    }

    .modern-checkbox:checked ~ .checkbox-text {
      color: #28a745;
      font-weight: 600;
    }

    .modern-checkbox:disabled ~ .checkbox-text {
      color: #6c757d;
    }

    @media (max-width: 576px) {
      .modern-messaging-options .col-xs-6 {
        width: 100%;
        margin-bottom: 5px;
      }
    }

    /* Modern T&C Label Styling */
    .modern-tc-label {
      display: inline-flex;
      align-items: center;
      padding: 6px 12px;
      border-radius: 4px;
      transition: all 0.2s ease;
      font-size: 13px;
      font-weight: 500;
      background: rgba(0,123,255,0.1);
      border: 1px solid rgba(0,123,255,0.2);
    }

    .modern-tc-label:hover {
      background: rgba(0,123,255,0.2);
      border-color: rgba(0,123,255,0.3);
      text-decoration: none;
    }

    /* Compact Summary Row Styling */
    .compact-summary-row {
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .summary-item {
      padding: 8px 4px;
      border-right: 1px solid #e9ecef;
    }

    .summary-item:last-child {
      border-right: none;
    }

    .summary-label {
      font-size: 11px;
      color: #6c757d;
      font-weight: 600;
      text-transform: uppercase;
      margin-bottom: 4px;
      letter-spacing: 0.5px;
    }

    .summary-value {
      font-size: 16px;
      font-weight: 700;
      color: #495057;
    }

    .grand-total .summary-value {
      color: #28a745;
      font-size: 18px;
    }

    /* Modern Button Styling */
    .modern-buttons-row {
      padding: 8px 0;
    }

    .modern-button-group {
      display: flex;
      gap: 6px;
      justify-content: space-between;
      margin: 0;
      flex-wrap: wrap;
    }

    .modern-btn {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 8px 6px;
      border: none;
      border-radius: 4px;
      font-size: 10px;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.3px;
      transition: all 0.2s ease;
      box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
      cursor: pointer;
      min-height: 38px;
      position: relative;
      overflow: hidden;
      margin: 0 !important;
      min-width: 0;
    }

    .modern-btn i {
      font-size: 12px;
      margin-bottom: 2px;
    }

    .modern-btn span {
      font-size: 9px;
      line-height: 1;
      white-space: nowrap;
    }

    .btn-hold {
      background: linear-gradient(135deg, #dc3545, #c82333);
      color: white;
      padding: 4px 8px !important;
      font-size: 11px !important;
      line-height: 1.2 !important;
      margin: 1px 2px !important;
    }

    .btn-hold:hover {
      background: linear-gradient(135deg, #c82333, #a71e2a);
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(220,53,69,0.2);
    }

    .btn-multiple {
      background: linear-gradient(135deg, #007bff, #0056b3);
      color: white;
      padding: 4px 8px !important;
      font-size: 11px !important;
      line-height: 1.2 !important;
      margin: 1px 2px !important;
    }

    .btn-multiple:hover {
      background: linear-gradient(135deg, #0056b3, #004085);
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(0,123,255,0.2);
    }

    .btn-cash {
      background: linear-gradient(135deg, #28a745, #1e7e34);
      color: white;
      padding: 4px 8px !important;
      font-size: 11px !important;
      line-height: 1.2 !important;
      margin: 1px 2px !important;
    }

    .btn-cash:hover {
      background: linear-gradient(135deg, #1e7e34, #155724);
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(40,167,69,0.2);
    }

    .btn-pay-all {
      background: linear-gradient(135deg, #6f42c1, #5a2d91);
      color: white;
      padding: 4px 8px !important;
      font-size: 11px !important;
      line-height: 1.2 !important;
      margin: 1px 2px !important;
    }

    .btn-pay-all:hover {
      background: linear-gradient(135deg, #5a2d91, #4e2a84);
      transform: translateY(-1px);
      box-shadow: 0 2px 4px rgba(111,66,193,0.2);
    }

    .modern-btn:hover {
      transform: translateY(-1px);
      box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
    }

    .modern-btn:active {
      transform: translateY(0);
      box-shadow: 0 1px 3px rgba(0,0,0,0.12);
    }

    /* General Button Compactness */
    .btn, button {
      padding: 4px 8px !important;
      font-size: 11px !important;
      line-height: 1.2 !important;
      margin: 1px 2px !important;
      border-radius: 3px !important;
    }

    .btn-xs {
      padding: 2px 6px !important;
      font-size: 10px !important;
      line-height: 1.1 !important;
    }

    .modern-btn:focus,
    .modern-btn:active {
      outline: none;
      box-shadow: 0 0 0 3px rgba(0,123,255,0.25);
    }

    /* Enhanced Items Table Height - Compact view optimized */
    .items_table_container {
      min-height: 300px !important;
      max-height: 400px !important;
      overflow-y: auto;
      border-radius: 6px;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      border: 1px solid #e0e6ed;
      margin-bottom: 8px !important;
    }

    .items_table {
      min-height: 270px;
      margin-bottom: 0 !important;
    }

    /* Compact Cart Styling - Improved readability */
    .items_table thead th {
      background: linear-gradient(135deg, #337ab7 0%, #2c5f9e 100%) !important;
      color: white !important;
      font-size: 12px !important;
      font-weight: 600 !important;
      padding: 8px 6px !important;
      text-align: center;
      border: 1px solid #2c5f9e !important;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .items_table tbody {
      font-size: 12px !important;
      font-weight: 500 !important;
    }

    .items_table tbody tr {
      height: 36px !important;
      line-height: 1.2 !important;
      transition: all 0.2s ease;
    }

    .items_table tbody tr:hover {
      background-color: rgba(0,123,255,0.05) !important;
      transform: scale(1.001);
    }

    .items_table tbody td {
      padding: 4px 6px !important;
      vertical-align: middle !important;
      border: 1px solid #ddd !important;
      font-size: 12px !important;
      line-height: 1.2 !important;
    }

    .items_table tbody td input {
      padding: 3px 6px !important;
      font-size: 12px !important;
      line-height: 1.2 !important;
      height: 26px !important;
      border-radius: 3px !important;
      border: 1px solid #ddd !important;
      width: 100% !important;
    }

    .items_table tbody td input:focus {
      border-color: #007bff !important;
      box-shadow: 0 0 0 2px rgba(0,123,255,0.1) !important;
      outline: none !important;
    }

    .items_table tbody td button {
      padding: 3px 5px !important;
      font-size: 11px !important;
      line-height: 1 !important;
      height: 24px !important;
      width: 24px !important;
      border-radius: 3px !important;
      margin: 0 !important;
      display: inline-flex !important;
      align-items: center !important;
      justify-content: center !important;
    }

    .items_table tbody td .btn-danger {
      background: linear-gradient(135deg, #dc3545 0%, #c82333 100%) !important;
      border-color: #dc3545 !important;
      color: white !important;
    }

    .items_table tbody td .btn-danger:hover {
      background: linear-gradient(135deg, #c82333 0%, #a71e2a 100%) !important;
      transform: scale(1.1) !important;
    }

    /* Compact table borders */
    .items_table {
      border-collapse: separate !important;
      border-spacing: 0 !important;
      border: 1px solid #ddd !important;
      border-radius: 6px !important;
      overflow: hidden !important;
    }

    /* Modern scrollbar for cart */
    .items_table_container::-webkit-scrollbar {
      width: 6px;
    }

    .items_table_container::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3px;
    }

    .items_table_container::-webkit-scrollbar-thumb {
      background: linear-gradient(135deg, #007bff, #0056b3);
      border-radius: 3px;
    }

    .items_table_container::-webkit-scrollbar-thumb:hover {
      background: linear-gradient(135deg, #0056b3, #004085);
    }

    /* Compact Quantity Controls - Improved readability */
    .compact-qty-btn {
      padding: 2px 5px !important;
      font-size: 11px !important;
      line-height: 1 !important;
      height: 24px !important;
      width: 24px !important;
      border-radius: 3px !important;
      margin: 0 !important;
      display: inline-flex !important;
      align-items: center !important;
      justify-content: center !important;
      background: #f8f9fa !important;
      border: 1px solid #ddd !important;
      transition: all 0.2s ease !important;
    }

    .compact-qty-btn:hover {
      background: #e9ecef !important;
      transform: scale(1.05) !important;
      border-color: #007bff !important;
    }

    .compact-qty-btn .fa {
      font-size: 9px !important;
    }

    .compact-qty-input {
      height: 24px !important;
      padding: 2px 4px !important;
      font-size: 12px !important;
      line-height: 1.2 !important;
      text-align: center !important;
      border: 1px solid #ddd !important;
    }

    .compact-qty-input:focus {
      border-color: #007bff !important;
      box-shadow: 0 0 0 1px rgba(0,123,255,0.1) !important;
      outline: none !important;
    }

    /* Remove button styling - Improved visibility */
    .items_table tbody td .fa-trash-o {
      color: #dc3545 !important;
      font-size: 16px !important;
      transition: all 0.2s ease !important;
      cursor: pointer !important;
    }

    .items_table tbody td .fa-trash-o:hover {
      color: #c82333 !important;
      transform: scale(1.2) !important;
    }

    /* Overall Page Polish */
    .box {
      transition: all 0.3s ease;
    }

    .form-control:focus {
      border-color: #007bff !important;
      box-shadow: 0 0 0 2px rgba(0,123,255,0.1) !important;
    }

    /* Input field improvements */
    input[type="text"], input[type="number"], select {
      transition: all 0.2s ease !important;
    }

    /* Smooth scrolling for containers */
    .items_table_container {
      scroll-behavior: smooth;
    }

    /* Right panel item list - Full height optimization - Increased by 10% */
    #items_search_list {
      height: calc(110vh - 224px) !important;
      max-height: none !important;
      overflow-y: auto !important;
      border: 1px solid #e0e6ed !important;
      border-radius: 4px !important;
      background: #fafafa !important;
      padding: 5px !important;
    }

    /* Ensure the item boxes are properly sized within the full height list */
    #items_search_list .item_box {
      margin-bottom: 8px;
      transition: all 0.2s ease;
    }

    #items_search_list .item_box:hover {
      transform: scale(1.02);
      box-shadow: 0 3px 8px rgba(0,0,0,0.15);
    }

    /* Custom scrollbar for the item list */
    #items_search_list::-webkit-scrollbar {
      width: 8px;
    }

    #items_search_list::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 4px;
    }

    #items_search_list::-webkit-scrollbar-thumb {
      background: linear-gradient(135deg, #007bff, #0056b3);
      border-radius: 4px;
    }

    #items_search_list::-webkit-scrollbar-thumb:hover {
      background: linear-gradient(135deg, #0056b3, #004085);
    }

    /* Responsive adjustments for different screen sizes - Increased by 10% */
    @media (max-height: 600px) {
      #items_search_list {
        height: calc(110vh - 200px) !important;
      }
    }

    @media (max-height: 800px) and (min-height: 601px) {
      #items_search_list {
        height: calc(110vh - 216px) !important;
      }
    }

    @media (min-height: 801px) {
      #items_search_list {
        height: calc(110vh - 240px) !important;
      }
    }

    /* Ensure content wrapper allows full height usage */
    .content-wrapper {
      min-height: calc(100vh - 50px) !important;
    }

    .box-info {
      margin-bottom: 5px !important;
    }

    /* Responsive adjustments for buttons */
    @media (max-width: 767px) {
      .modern-button-group {
        flex-wrap: wrap;
      }

      .modern-btn {
        flex: 1 1 calc(50% - 4px);
        margin-bottom: 8px;
      }
    }

    @media (max-width: 576px) {
      .summary-item {
        border-right: none;
        border-bottom: 1px solid #e9ecef;
        padding: 6px 4px;
      }

      .summary-item:last-child {
        border-bottom: none;
      }

      .summary-label {
        font-size: 10px;
      }

      .summary-value {
        font-size: 14px;
      }

      .modern-btn {
        flex: 1 1 100%;
        flex-direction: row;
        justify-content: center;
        min-height: 45px;
        padding: 8px 12px;
      }

      .modern-btn i {
        margin-bottom: 0;
        margin-right: 6px;
        font-size: 16px;
      }

      .modern-btn span {
        font-size: 12px;
      }
    }
  </style>
</head>

<!-- ADD THE CLASS layout-top-nav TO REMOVE THE SIDEBAR. -->
<body class="hold-transition skin-blue layout-top-nav">
  <?php $CI =& get_instance(); ?>
<div class="wrapper">
  
  
  <header class="main-header">
    <nav class="navbar navbar-static-top">
      <div class="container">
        <div class="navbar-header">
          <a href="<?php echo $base_url; ?>dashboard" class="navbar-brand" title="Go to Dashboard!"><b class="hidden-xs"><?= $this->session->userdata('store_name'); ?></b><b class="hidden-lg">POS</b></a>
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
            <i class="fa fa-bars"></i>
          </button>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse pull-left" id="navbar-collapse">
          <ul class="nav navbar-nav">
            <?php if($CI->permissions('sales_view')) { ?>
            <li class=""><a href="<?php echo $base_url; ?>sales" title="View Sales List!"><i class="fa fa-list text-yellow" ></i> <span><?= $this->lang->line('sales_list'); ?></span></a></li>
            <?php } ?>
            
            <?php if($CI->permissions('customers_view')) { ?>
            <li class=""><a href="<?php echo $base_url; ?>customers/" title="View Customers List"><i class="fa  fa-group  text-yellow " ></i> <span><?= $this->lang->line('customers_list'); ?></span></a></li>
            <?php } ?>
            <?php if($CI->permissions('items_view')) { ?>
            <li class=""><a href="<?php echo $base_url; ?>items/" title="View Items List"><i class="fa  fa-cubes text-yellow " ></i> <span><?= $this->lang->line('items_list'); ?></span></a></li>
            <?php } ?>
            <?php if($CI->permissions('sales_add')) { ?>
            <li class=""><a href="<?php echo $base_url; ?>pos" title="Create New POS Invoice"><i class="fa fa-calculator text-yellow " ></i> <span><?= $this->lang->line('new_invoice'); ?></span></a></li>
            <?php } ?>
          </ul>
        </div>
        <!-- /.navbar-collapse -->
        <!-- Navbar Right Menu -->
        <div class="navbar-custom-menu">
          <ul class="nav navbar-nav">
            
            <!-- User Account Menu -->
            <li class="dropdown user user-menu">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" title="Click To View Hold Invoices">
             
              <span class=""><?= $this->lang->line('hold_list'); ?></span>
              <span class="label label-danger hold_invoice_list_count"><?=$tot_count?></span>
            </a>

            <ul class="dropdown-menu dropdown-width-lg">
              
              <!-- Menu Body -->
              <li class="user-body">
                <div class="row">
                  <div class="col-xs-12 text-center " style="max-height:300px;overflow-y: scroll;">
                    <table class="table table-bordered" width="100%">
                      <thead>
                      <tr>
                        <th>ID</th>
                        <th>Date</th>
                        <th>Ref.ID</th>
                        <th>Action</th>
                      </tr>
                      </thead>
                      <tbody id="hold_invoice_list" >
                       <?=$result?>
                      </tbody>
                    </table>
                  </div>
                </div>
                <!-- /.row -->
              <!--</li>-->
            </ul>
          </li>

            <!-- Messages: style can be found in dropdown.less-->
            <li class="hidden-xs" id="fullscreen"><a title="Fullscreen On/Off"><i class="fa fa-tv text-white" ></i> </a></li>
            <li class="text-center" id="">
            <a title="Dashboard" href="<?php echo $base_url; ?>dashboard"><i class="fa fa-dashboard text-yellow" ></i><b class="hidden-xs"><?= $this->lang->line('dashboard'); ?></b></a>
          </li>

            <!-- User Account Menu -->
            <li class="dropdown user user-menu">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">
              <img src="<?php echo get_profile_picture(); ?>" class="user-image" alt="User Image">
              <span class="hidden-xs"><?php print ucfirst($this->session->userdata('inv_username')); ?></span>
            </a>

            <ul class="dropdown-menu">
              <!-- User image -->
              <li class="user-header">
                <img src="<?php echo get_profile_picture(); ?>" class="img-circle" alt="User Image">

                <p>
                 <?php print ($this->session->userdata('inv_username')); ?>
                  <small>Year <?=date("Y");?></small>
                  <small class='text-uppercase text-bold'>Role: <?=$this->session->userdata('role_name');?></small>
                </p>
              </li>
              <!-- Menu Body -->
              <!-- Menu Footer-->
              <li class="user-footer">
                <div class="pull-left">
                  <a href="<?php echo $base_url; ?>users/edit/<?= $this->session->userdata('inv_userid'); ?>" class="btn btn-default btn-flat">Profile</a>
                </div>
                <div class="pull-right">
                  <a href="<?php echo $base_url; ?>logout" class="btn btn-default btn-flat">Sign out</a>
                </div>
              </li>
            </ul>
          </li>
          </ul>
        </div>
        <!-- /.navbar-custom-menu -->
      </div>
      <!-- /.container-fluid -->
    </nav>
  </header>

  <?php $css = ($this->session->userdata('language')=='Arabic' || $this->session->userdata('language')=='Urdu') ? 'margin-right: 0 !important;': '';?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper" style="<?=$css;?>">
    <!-- Content Header (Page header) -->
   <!--  <section class="content-header">
      <h1>
        General Form Elements
        <small>Preview</small>
      </h1>
      <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
        <li><a href="#">Forms</a></li>
        <li class="active">General Elements</li>
      </ol>
    </section> -->

    <!-- **********************MODALS***************** -->
    <?php include"modals/modal_customer.php"; ?>
    <?php include"modals/modal_sales_item.php"; ?>
    <?php include"modals/modal_item.php"; ?>
    <?php include"modals/modal_item_or_service.php"; ?>
    <?php include"modals/modal_expense.php"; ?>
    <?php include"modals/modal_daily_summary.php"; ?>
    
    <!-- Customer Action Modals -->
    <div class="pay_now_modal"></div>
    <div class="pay_return_due_modal"></div>
    <div class="bulk_payment_list_modal"></div>
    
    <?php /*include"modals/modal_service.php";*/ ?>

    
    <!-- **********************MODALS END***************** -->
    <!-- Main content -->
    <section class="content">
      <div class="row">
        <!-- left column -->
        <div class="col-md-7">
         
          <!-- general form elements -->
          <div class="box box-primary">
            <!-- form start -->
            <form class="form-horizontal" id="pos-form" >
            <div class="box-header with-border" style="padding-bottom: 0px;">
              <div class="row" >
                <div class="col-md-12" >
               
                  
                <?php if(isset($sales_id)): ?>
                  <?php if($CI->permissions('sales_add')) { ?>
                  <div class="col-md-4 pull-right">
                    <a href='<?= $base_url;?>pos' class="btn btn-primary pull-right">New Invoice</a>
                  </div>
                  <?php } ?>
                <?php endif; ?>
                
              </div>
              </div>
               
            
            
            
          </div>
            <!-- /.box-header -->
            
              <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
              <input type="hidden" value='0' id="hidden_rowcount" name="hidden_rowcount">
              <input type="hidden" value='' id="hidden_invoice_id" name="hidden_invoice_id">
              <input type="hidden" id="base_url" value="<?php echo $base_url;; ?>">
              <input type="hidden" class="scroll_or_not" value="true">
              <input type="hidden" id="hidden_sales_type_id" name="sales_type_id" value="<?= $sales_type_id ?>">
              <?php if(isset($sales_id) && !empty($sales_id)): ?>
              <input type="hidden" id="sales_id" name="sales_id" value="<?php echo $sales_id; ?>">
              <?php endif; ?>

              
              <input type="hidden" value='' id="walk_in_customer_name" value="<?=get_walk_in_customer_name();?>">
              
              <!-- **********************MODALS***************** -->
             <?php include"modals_pos_payment/modal_payments_multi.php"; ?>

             <?php include"modals/modal_terms.php"; ?>

              <!-- **********************MODALS END***************** -->
              <!-- **********************MODALS***************** -->
              <div class="modal fade" id="discount-modal" tabindex='-1'>
                <div class="modal-dialog">
                  <div class="modal-content">
                    <div class="modal-header">
                      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                      <h4 class="modal-title">Set Discount</h4>
                    </div>
                    <div class="modal-body">
                      
                        <div class="row">
                          <div class="col-md-6">
                            <div class="box-body">
                              <div class="form-group">
                                <label for="discount_input">Discount</label>
                                <input type="text" class="form-control" id="discount_input" name="discount_input" placeholder="" value="0">
                              </div>
                            </div>
                          </div>
                          <div class="col-md-6">
                            <div class="box-body">
                              <div class="form-group">
                                <label for="discount_type">Discount Type</label>
                                <select class="form-control" id='discount_type' name="discount_type">
                                  <option value='in_percentage'>Per%</option>
                                  <option value='in_fixed'>Fixed</option>
                                </select>
                              </div>
                            </div>
                          </div>
                        </div>
                     
                    </div>
                    <div class="modal-footer">
                      <button type="button" class="btn btn-warning" data-dismiss="modal">Close</button>
                      <button type="button" class="btn btn-primary discount_update">Update</button>
                    </div>
                  </div>
                  <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
              </div>
              <!-- /.modal -->
              <!-- **********************MODALS END***************** -->
              <div class="box-body compact-section" style="padding: 8px 15px;">                
              <!-- Store Code -->
              <?php $store_id=''; ?>
            <?php 
             /*if(store_module() && is_admin()) {$this->load->view('store/store_code',array('show_store_select_box_2'=>true,'store_id'=>$store_id)); }else{*/
                echo "<input type='hidden' name='store_id' id='store_id' value='".get_current_store_id()."'>";
              /*}*/
              ?>
            <!-- Store Code end -->


              <div class="row pos-top-row" style="margin-bottom: 10px;">
                <div class="col-md-3" style="padding-right: 5px;">
                  <div class="input-group input-group-sm" data-toggle="tooltip" title="Sales Type">
                    <span class="input-group-addon"><i class="fa fa-tag text-blue"></i></span>
                     <select class="form-control select2" id="sales_type_id" name="sales_type_id" style="width: 100%;">
                          <?= get_sales_types_select_list($sales_type_id); ?>
                      </select>
                  </div>
                </div>
                <div class="col-md-3" style="padding-left: 5px; padding-right: 5px;">
                  <div class="input-group input-group-sm" data-toggle="tooltip" title="Warehouse">
                    <span class="input-group-addon" ><i class="fa fa-building text-red"></i></span>
                     <select class="form-control select2" id="warehouse_id" name="warehouse_id"  style="width: 100%;"  >
                          <?= get_warehouse_select_list($warehouse_id,get_current_store_id()); ?>
                      </select>
                   
                  </div>
                  
                </div>
                <div class="col-md-3" style="padding-left: 5px; padding-right: 5px;">
                  <div class="input-group input-group-sm" data-toggle="tooltip" title="Invoice Initial Code">
                    <span class="input-group-addon"><i class="fa fa-th-list"></i></span>
                     <input type="text" class="form-control" placeholder="Init Code" id="init_code" name="init_code" value="<?= $init_code ?>" readonly>
                  </div>
                </div>
                <div class="col-md-3" style="padding-left: 5px;">
                  <div class="input-group input-group-sm" data-toggle="tooltip" title="Invoice Count ID">
                    <span class="input-group-addon"><i class="fa fa-hashtag"></i></span>
                     <input type="text" class="form-control" placeholder="Invoice No" id="count_id" name="count_id" value="<?= $count_id ?>" readonly>
                  </div>
                </div> 

              </div><!-- row end -->

              <div class="row pos-customer-row" style="margin-bottom: 10px;">
                <div class="col-md-6" style="padding-right: 5px;">
                  <div class="input-group input-group-sm" data-toggle="tooltip" title="Customer">
                    <span class="input-group-addon" ><i class="fa fa-user"></i></span>
                     <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 class="customer_points text-success" style="display: none;"></span>
                    <div class="customer-due-section" style="margin-top: 5px;">
                      <lable style="font-size: 12px; margin-bottom: 0;"><?= $this->lang->line('previous_due'); ?> :<label class="customer_previous_due text-red" style="font-size: 12px; margin-left: 5px;"><?=store_number_format(0)?></label></lable>
                      <div style="margin-top: 3px;">
                        <button type="button" id="customer_action_btn" class="btn btn-xs btn-primary" style="display: none;" title="Customer Actions">
                          <i class="fa fa-cog"></i> Action
                        </button>
                        <button type="button" id="expense_btn" class="btn btn-xs btn-success" data-toggle="modal" data-target="#expense-modal" title="Add Expense (Alt+E)">
                          <i class="fa fa-money"></i> Expense
                        </button>
                        <button type="button" id="summary_btn" class="btn btn-xs btn-info" data-toggle="modal" data-target="#daily-summary-modal" title="Daily Summary (Alt+S)">
                          <i class="fa fa-line-chart"></i> Summary
                        </button>
                        <button type="button" id="stock_adj_btn" class="btn btn-xs btn-danger" title="Stock Adjustment (Alt+T)">
                          <i class="fa fa-exchange"></i> Stock Adj
                        </button>
                      </div>
                    </div>
                  
                  
                </div>
                <div class="col-md-6" style="padding-left: 5px;">
                  <div class="input-group input-group-sm" data-toggle="tooltip" title="Select Items">
                    <span class="input-group-addon" ><i class="fa fa-barcode"></i></span>
                     <input type="text" class="form-control" placeholder="Item name/Barcode/Itemcode" id="item_search">
                     <span class="input-group-addon pointer show_item_service" title="New Item?"><i class="fa fa-plus text-primary fa-lg"></i></span>
                  </div>
                </div>                
              </div><!-- row end -->
             
              <div class="row" style="margin-bottom: 8px;">
                <div class="col-md-12">
                  <div class="form-group" style="margin-bottom: 0;">
                    <div class="col-sm-12 items_table_container" >
                      <table class="table table-condensed table-bordered table-responsive items_table">
                        <thead>
                          <th width="28%"><?= $this->lang->line('item_name'); ?></th>
                          <th width="8%"><?= $this->lang->line('stock'); ?></th>
                          <th width="20%"><?= $this->lang->line('quantity'); ?></th>
                          <th width="12%"><?= $this->lang->line('price'); ?></th>
                          <th width="8%"><?= $this->lang->line('discount'); ?>(<?=$CI->currency()?>)</th>
                          <th width="8%"><?= $this->lang->line('tax'); ?></th>
                          <th width="12%"><?= $this->lang->line('subtotal'); ?></th>
                          <th width="4%"><i class="fa fa-close"></i></th>
                        </thead>
                        <tbody id="pos-form-tbody">
                          <!-- body code -->
                        </tbody>        
                        <tfoot>
                          <!-- footer code -->
                        </tfoot>              
                      </table>
                    </div>
                  </div>
                </div>
              </div>

              <div class="row" style="margin-bottom: 8px;">
                 <!-- SMS Sender while saving -->
                      <?php 
                         //Change Return
                          $send_sms_checkbox='disabled';
                          if($CI->is_sms_enabled()){
                            if(!isset($sales_id)){
                              $send_sms_checkbox='checked';  
                            }else{
                              $send_sms_checkbox='';
                            }
                          }

                          // WhatsApp Sender while saving
                          $send_whatsapp_checkbox='disabled';
                          if($CI->is_whatsapp_enabled()){
                            if(!isset($sales_id)){
                              $send_whatsapp_checkbox='checked';  
                            }else{
                              $send_whatsapp_checkbox='';
                            }
                          }

                    ?>
                   
                    <div class="col-xs-12">
                        <div class="row modern-messaging-options" style="background: #f8f9fa; padding: 6px 10px; border-radius: 4px; margin: 2px 0;">
                            <div class="col-xs-4">
                                <div class="modern-checkbox-group">
                                    <label class="modern-checkbox-label">
                                        <input type="checkbox" <?=$send_sms_checkbox;?> id="send_sms" name="send_sms" class="modern-checkbox">
                                        <span class="modern-checkmark"></span>
                                        <i class="fa fa-sms text-primary" style="margin-right: 4px;"></i>
                                        <span class="checkbox-text">Send SMS</span>
                                        <i class="fa fa-info-circle text-muted hover-q" style="margin-left: 3px; font-size: 10px;" 
                                           data-container="body" data-toggle="popover" data-placement="top" 
                                           data-content="Send SMS notification to customer mobile number" 
                                           data-html="true" data-trigger="hover" title="SMS Notification"></i>
                                    </label>
                                </div>
                            </div>
                            <div class="col-xs-4">
                                <div class="modern-checkbox-group">
                                    <label class="modern-checkbox-label">
                                        <input type="checkbox" <?=$send_whatsapp_checkbox;?> id="send_whatsapp" name="send_whatsapp" class="modern-checkbox">
                                        <span class="modern-checkmark"></span>
                                        <i class="fa fa-whatsapp text-success" style="margin-right: 4px;"></i>
                                        <span class="checkbox-text">Send WhatsApp</span>
                                        <i class="fa fa-info-circle text-muted hover-q" style="margin-left: 3px; font-size: 10px;" 
                                           data-container="body" data-toggle="popover" data-placement="top" 
                                           data-content="Send WhatsApp message with invoice details and link" 
                                           data-html="true" data-trigger="hover" title="WhatsApp Message"></i>
                                    </label>
                                </div>
                            </div>
                            <div class="col-xs-4 text-center">
                                <label class="control-label text-blue pointer modern-tc-label" toggle="tooltip" title="<?= $this->lang->line('edit_invoice_tc')?>" data-toggle="modal" data-target="#terms-modal">
                                    <i class="fa fa-list-alt" style="margin-right: 4px;"></i>
                                    <span>Terms & Conditions</span>
                                </label>
                                <div class="hide div2 text-center" style="margin-top: 2px; font-size: 10px;">
                                    <span class="text-success">Coupon Applied: </span>
                                    <span class="coupon_value text-success">0.00</span> 
                                    <span class="coupon_type text-success"></span>
                                </div>
                            </div>
                        </div>
                    </div> 
                </div>
           
              </div>
              <!-- /.box-body -->

              <div class="box-footer bg-gray" style="padding: 8px 15px;">
                <!-- Compact Summary Row -->
                <div class="row compact-summary-row" style="background: #fff; padding: 8px 10px; margin: 0 -15px 10px -15px; border-top: 1px solid #e0e6ed; border-bottom: 1px solid #e0e6ed;">
                  <div class="col-xs-3 text-center summary-item">
                    <div class="summary-label">Quantity</div>
                    <div class="summary-value tot_qty">0</div>
                  </div>
                  <div class="col-xs-3 text-center summary-item">
                    <div class="summary-label">Total Amount</div>
                    <div class="summary-value"><?= $CI->currency('<span class="tot_amt">0.00</span>');?></div>
                  </div>
                  <div class="col-xs-3 text-center summary-item">
                    <div class="summary-label">Total Discount <a class="fa fa-pencil-square-o cursor-pointer" data-toggle="modal" data-target="#discount-modal" style="font-size: 10px; margin-left: 3px;"></a></div>
                    <div class="summary-value"><?= $CI->currency('<span class="tot_disc">0.00</span>');?></div>
                  </div>
                  <div class="col-xs-3 text-center summary-item">
                    <div class="summary-label">Grand Total</div>
                    <div class="summary-value grand-total"><?= $CI->currency('<span class="tot_grand">0.00</span>');?></div>
                  </div>
                </div>
               
               <!-- Modern Compact Buttons Row -->
               <div class="row modern-buttons-row" style="margin-bottom: 0;">
                  <?php if(isset($sales_id)){ $btn_id='update';$btn_name="Cash"; ?>
                    <input type="hidden" name="sales_id" id="sales_id" value="<?php echo $sales_id;?>"/>
                  <?php } else{ $btn_id='save';$btn_name="Cash";} ?>

                  <div class="col-xs-12">
                    <div class="modern-button-group">
                      <button type="button" id="hold_invoice" name="" class="modern-btn btn-hold <?php if(isset($sales_id)) echo 'disabled'; ?>" title="Hold Invoice [Alt+H]" <?php if(isset($sales_id)) echo 'disabled'; ?>>
                        <i class="fa fa-hand-paper-o"></i>
                        <span>Hold</span>
                      </button>
                      
                      <button type="button" name="" class="modern-btn btn-multiple show_payments_modal" title="Multiple Payments [Alt+M]">
                        <i class="fa fa-credit-card"></i>
                        <span>Multiple</span>
                      </button>
                      
                      <button type="button" id="show_cash_modal" name="" class="modern-btn btn-cash Alt_c <?php if(isset($sales_id)) echo 'disabled'; ?>" title="By Cash & Save [Alt+C]" <?php if(isset($sales_id)) echo 'disabled'; ?>>
                        <i class="fa fa-money"></i>
                        <span><?php echo $btn_name;?></span>
                      </button>

                      <button type="button" id="pay_all" name="" class="modern-btn btn-pay-all Alt_a <?php if(isset($sales_id)) echo 'disabled'; ?>" title="Pay All & Save [Alt+A]" <?php if(isset($sales_id)) echo 'disabled'; ?>>
                        <i class="fa fa-check-circle"></i>
                        <span>Pay All</span>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </form>
          </div>
          <!-- /.box -->
        </div>
        <!--/.col (left) -->
        <!-- right column -->
        <div class="col-md-5">
          <!-- Horizontal Form -->
          <div class="box box-info">
            <!-- form start -->
            
              <div class="box-body" style="padding: 8px 15px;">
                
              <div class="row" style="margin-bottom: 8px;">

                <div class="col-md-6" style="padding-right: 5px;">
                  <div class="input-group input-group-sm">
                      <select class="form-control select2" id="category_id" name="category_id"  style="width: 100%;"  >
                        <option value="">-All Categories-</option>
                        <?= get_categories_select_list();  ?>
                      </select>
                          <span class="input-group-btn">
                            <button type="button" class="btn text-blue btn-flat reset_categories" title="Reset Categories" data-toggle="tooltip" data-placement="top">
                              <i class="fa fa-undo"></i>
                            </button>
                          </span>
                    </div>
                </div>


                <div class="col-md-6" style="padding-left: 5px;">
                  <div class="input-group input-group-sm">
                      <select class="form-control select2" id="brand_id" name="brand_id"  style="width: 100%;"  >
                        <option value="">-All Brands-</option>
                        <?= get_brands_select_list();  ?>
                      </select>
                          <span class="input-group-btn">
                            <button type="button" class="btn text-blue btn-flat reset_brands" title="Reset Brand" data-toggle="tooltip" data-placement="top">
                              <i class="fa fa-undo"></i>
                            </button>
                          </span>
                    </div>
                </div>                

              </div><!-- row end -->

              <div class="row" style="margin-bottom: 10px;">

                <div class="col-md-12">
                  <div class="input-group input-group-sm">
                   
                      <input type="text" class="form-control" data-toggle="tooltip" title="Enter Item Name" placeholder="Item Name" id="item_name" name="item_name">

                          <span class="input-group-btn">
                            <button type="button" class="btn text-blue btn-flat reset_item_name" title="Reset Item Name" data-toggle="tooltip" data-placement="top">
                              <i class="fa fa-undo"></i>
                            </button>
                          </span>
                    </div>
                </div>               

              </div><!-- row end -->


             
              <div class="row">
                <div class="col-md-12">
                  <div style="margin-bottom: 0;">
                    <section class="content .sec_div" style="padding: 0;">
                      <div class="row search_div" id="items_search_list" style="overflow-y: auto; min-height: 100px; max-height: calc(100vh - 300px); padding: 5px; border: 1px solid #e0e6ed; border-radius: 4px; background: #fafafa;">
                      </div>
                      <h4 class='text-danger text-center error_div' style="display: none; margin: 20px 0; font-size: 14px;">No More Records Found</h4>
                    </section>
                    <div class="ajax-load text-center" style="display:none; padding: 10px;">
                        <button type="button" class="btn btn-default btn-sm ajax" title="Ajax Request">
                        <i class="fa fa-spin fa-refresh"></i>&nbsp; Loading More Data
                      </button>
                      </div>
                  </div>
                </div>
              </div>
           
              </div>
              <!-- /.box-body -->

              
           
          </div>
          <!-- /.box -->
          
          <!-- /.box -->
        </div>
        <!--/.col (right) -->
      </div>
      <!-- /.row -->
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->

  <?php include"footer.php";?>
</div>
<!-- ./wrapper -->

<!-- SOUND CODE -->
<?php include"comman/code_js_sound.php"; ?>
<!-- GENERAL CODE -->
<?php include"comman/code_js.php"; ?>

<!-- iCheck -->
<script src="<?php echo $theme_link; ?>plugins/iCheck/icheck.min.js"></script>

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

<!-- DROP DOWN -->
<script src="<?php echo $theme_link; ?>dist/js/bootstrap3-typeahead.min.js"></script>  
<!-- DROP DOWN END-->

<script type="text/javascript">
  
  var warehouse_module=false;
  <?php if(warehouse_module() && warehouse_count()>1){ ?> 
    warehouse_module=true;
  <?php } ?>

  var store_module=false;
  <?php if(store_module()){ ?> 
    store_module=true;
  <?php } ?>

  // Fullscreen state management
  var fullscreen_enabled = false;
  
  // Override the fullscreen toggle to track state
  $(document).ready(function() {
    // Track fullscreen state changes
    $(document).on('fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange', function() {
      fullscreen_enabled = !!(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement);
      localStorage.setItem('pos_fullscreen_state', fullscreen_enabled);
    });
    
    // Restore fullscreen state on page load
    var saved_fullscreen_state = localStorage.getItem('pos_fullscreen_state');
    if (saved_fullscreen_state === 'true') {
      setTimeout(function() {
        enterFullscreen();
      }, 500); // Small delay to ensure page is fully loaded
    }
    
    // Handle window focus events to restore fullscreen when returning from print
    $(window).on('focus', function() {
      var should_be_fullscreen = localStorage.getItem('pos_fullscreen_state') === 'true';
      if (should_be_fullscreen && !fullscreen_enabled) {
        setTimeout(function() {
          enterFullscreen();
        }, 100);
      }
    });
    
    // Handle visibility change events (when tab becomes visible again)
    $(document).on('visibilitychange', function() {
      if (!document.hidden) {
        var should_be_fullscreen = localStorage.getItem('pos_fullscreen_state') === 'true';
        if (should_be_fullscreen && !fullscreen_enabled) {
          setTimeout(function() {
            enterFullscreen();
          }, 200);
        }
      }
    });
    
    // Add a click listener to restore fullscreen on any user interaction
    $(document).on('click', function(e) {
      // Only restore if user clicks on main content areas, not buttons that might cause issues
      if (!$(e.target).closest('button, .btn, .modal').length) {
        var should_be_fullscreen = localStorage.getItem('pos_fullscreen_state') === 'true';
        if (should_be_fullscreen && !fullscreen_enabled) {
          enterFullscreen();
        }
      }
    });
    
    // Monitor for fullscreen state changes and restore immediately
    var fullscreenMonitor = setInterval(function() {
      var should_be_fullscreen = localStorage.getItem('pos_fullscreen_state') === 'true';
      if (should_be_fullscreen && !fullscreen_enabled) {
        enterFullscreen();
      }
    }, 50); // Continuous monitoring every 50ms
    
    // Stop continuous monitoring after 5 minutes to prevent performance issues
    setTimeout(function() {
      clearInterval(fullscreenMonitor);
    }, 300000);
    
    // Override the fullscreen button click
    $("#fullscreen").off('click').on("click", function() {
      if (fullscreen_enabled) {
        exitFullscreen();
      } else {
        enterFullscreen();
      }
    });
  });
  
  function enterFullscreen() {
    var element = document.documentElement;
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen();
    }
  }
  
  function exitFullscreen() {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  }
  
  // Function to restore fullscreen after operations
  function restoreFullscreenIfNeeded() {
    var saved_fullscreen_state = localStorage.getItem('pos_fullscreen_state');
    if (saved_fullscreen_state === 'true' && !fullscreen_enabled) {
      setTimeout(function() {
        enterFullscreen();
      }, 1000); // Delay to allow page operations to complete
    }
  }
  
  // Override the save function to restore fullscreen mode after save
  window.original_save = window.save;
  window.save = function(print=false, pay_all=false) {
    // Store fullscreen state before save
    var was_fullscreen = fullscreen_enabled;
    localStorage.setItem('pos_fullscreen_state_before_save', was_fullscreen);
    
    // Call original save function
    if (typeof window.original_save === 'function') {
      window.original_save(print, pay_all);
    }
    
    // Restore fullscreen after save completes (with delay for async operations)
    setTimeout(function() {
      if (localStorage.getItem('pos_fullscreen_state_before_save') === 'true') {
        restoreFullscreenIfNeeded();
      }
    }, 2000);
  };
</script>
<script src="<?php echo $theme_link; ?>js/pos.js"></script>
<script>
  // After pos.js loads, override functions to maintain fullscreen state
  $(document).ready(function() {
    // Store original functions
    if (typeof window.save !== 'undefined') {
      window.original_pos_save = window.save;
      
      // Override save function to restore fullscreen
      window.save = function(print=false, pay_all=false) {
        var was_fullscreen = fullscreen_enabled;
        
        // For print operations, start monitoring immediately before calling save
        if (print && was_fullscreen) {
          localStorage.setItem('pos_fullscreen_state', 'true');
          
          // Start monitoring immediately with very high frequency
          var immediateRestore = setInterval(function() {
            if (!fullscreen_enabled) {
              enterFullscreen();
            }
          }, 5); // Check every 5ms for ultra-responsive restoration
          
          // Call original save function
          var result = window.original_pos_save(print, pay_all);
          
          // Continue monitoring for 45 seconds
          setTimeout(function() {
            clearInterval(immediateRestore);
          }, 45000);
          
          return result;
        } else {
          // Call original save function for non-print operations
          var result = window.original_pos_save(print, pay_all);
          
          if (was_fullscreen) {
            // For non-print operations, use normal delay
            setTimeout(function() {
              if (!fullscreen_enabled) {
                enterFullscreen();
              }
            }, 2000);
          }
          
          return result;
        }
      };
    }
    
    // Override window.open to prevent fullscreen exit during print operations
    var original_window_open = window.open;
    window.open = function(url, target, features) {
      var was_fullscreen = fullscreen_enabled;
      
      // If we were in fullscreen and this looks like a print operation, maintain fullscreen
      if (was_fullscreen && url && url.includes('print_invoice_pos')) {
        // Store the fullscreen state immediately
        localStorage.setItem('pos_fullscreen_state', 'true');
        
        // Use a very short delay to allow the print window to start opening
        setTimeout(function() {
          // Call original window.open
          var popup = original_window_open.call(window, url, target, features);
          
          // Immediately start aggressive fullscreen maintenance
          var maintainFullscreen = setInterval(function() {
            if (!fullscreen_enabled) {
              enterFullscreen();
            }
          }, 10); // Check every 10ms for very immediate restoration
          
          // Stop maintaining after 30 seconds
          setTimeout(function() {
            clearInterval(maintainFullscreen);
          }, 30000);
          
          return popup;
        }, 50);
        
        // Return a dummy window object to prevent errors
        return { closed: false };
      } else {
        // Call original window.open for non-print operations
        return original_window_open.call(this, url, target, features);
      }
    };
    
    // Override hold_invoice function if it exists
    if (typeof window.hold_invoice_list !== 'undefined') {
      window.original_hold_invoice_list = window.hold_invoice_list;
      
      window.hold_invoice_list = function() {
        var was_fullscreen = fullscreen_enabled;
        var result = window.original_hold_invoice_list();
        
        if (was_fullscreen) {
          setTimeout(function() {
            if (!fullscreen_enabled) {
              enterFullscreen();
            }
          }, 1500);
        }
        
        return result;
      };
    }
    
    // Override payment button handlers to maintain fullscreen
    $(document).off('click', '#show_cash_modal, .Alt_c').on('click', '#show_cash_modal, .Alt_c', function(e) {
      var was_fullscreen = fullscreen_enabled;
      localStorage.setItem('pos_fullscreen_state', was_fullscreen);
      
      // Let the original handler run first
      setTimeout(function() {
        // Add fullscreen restoration to the modal's save operation
        $('#multiple-payments-modal').off('hidden.bs.modal.fullscreen').on('hidden.bs.modal.fullscreen', function() {
          if (was_fullscreen) {
            setTimeout(function() {
              if (!fullscreen_enabled) {
                enterFullscreen();
              }
            }, 500);
          }
        });
        
        // Also monitor for print operations from this modal
        $('#multiple-payments-modal').find('.make_sale').off('click.fullscreen').on('click.fullscreen', function() {
          if (was_fullscreen) {
            var aggressiveRestore = setInterval(function() {
              if (!fullscreen_enabled) {
                enterFullscreen();
              }
            }, 100);
            
            setTimeout(function() {
              clearInterval(aggressiveRestore);
            }, 60000);
          }
        });
      }, 100);
    });
    
    // Override multiple payment modal to restore fullscreen
    $(document).off('click', '.show_payments_modal').on('click', '.show_payments_modal', function(e) {
      var was_fullscreen = fullscreen_enabled;
      
      setTimeout(function() {
        $('#multiple-payments-modal').off('hidden.bs.modal.fullscreen').on('hidden.bs.modal.fullscreen', function() {
          if (was_fullscreen) {
            setTimeout(function() {
              if (!fullscreen_enabled) {
                enterFullscreen();
              }
            }, 500);
          }
        });
      }, 100);
    });
    
    // Monitor for successful save operations and restore fullscreen
    var original_toastr_success = toastr.success;
    toastr.success = function(message) {
      var was_fullscreen = localStorage.getItem('pos_fullscreen_state') === 'true';
      var result = original_toastr_success.apply(this, arguments);
      
      // If the success message indicates a save operation, restore fullscreen immediately
      if (message && message.toLowerCase().includes('saved successfully') && was_fullscreen) {
        // Start immediate restoration without any delay
        var immediateRestore = setInterval(function() {
          if (!fullscreen_enabled) {
            enterFullscreen();
          }
        }, 1); // Check every 1ms for instant restoration
        
        // Stop after 30 seconds
        setTimeout(function() {
          clearInterval(immediateRestore);
        }, 30000);
      }
      
      return result;
    };
    
    // Override jQuery AJAX to catch successful save operations immediately
    var original_ajax = $.ajax;
    $.ajax = function(options) {
      var was_fullscreen = fullscreen_enabled;
      
      // If this looks like a save operation to pos controller
      if (options.url && options.url.includes('pos/pos_save_update') && was_fullscreen) {
        localStorage.setItem('pos_fullscreen_state', 'true');
        
        // Store original success callback
        var original_success = options.success;
        
        // Override success callback
        options.success = function(result) {
          // Start immediate fullscreen restoration as soon as AJAX succeeds
          var ultraFastRestore = setInterval(function() {
            if (!fullscreen_enabled) {
              enterFullscreen();
            }
          }, 1); // Check every 1ms
          
          // Stop after 30 seconds
          setTimeout(function() {
            clearInterval(ultraFastRestore);
          }, 30000);
          
          // Call original success callback
          if (original_success) {
            return original_success.apply(this, arguments);
          }
        };
      }
      
      // Call original AJAX
      return original_ajax.call(this, options);
    };
  });
</script>
<script>

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

         $(document).ready(function () {

            // var customer_id = "<?= (!empty($customer_id)) ? $customer_id : '';  ?>";

            // autoLoadFirstCustomer(customer_id);

         });
         //Customer Selection Box Search - END


    var base_url=$("#base_url").val();
    
    /*Sales Type Invoice Code Update*/
    $("#sales_type_id").on("change",function(){
      var sales_type_id=$(this).val();
      $("#hidden_sales_type_id").val(sales_type_id);
      $.post(base_url+"pos/get_sales_type_invoice_data",{sales_type_id:sales_type_id},function(result){
          var data = JSON.parse(result);
          $("#init_code").val(data.init_code);
          $("#count_id").val(data.count_id);
      });
    });

    /*$("#store_id").on("change",function(){
      var store_id=$(this).val();
      $.post(base_url+"sales/get_customers_select_list",{store_id:store_id},function(result){
          $("#customer_id").html('').append(result).select2();
          <?php if(isset($sales_id) && empty($sales_id)){ ?>
            $(".items_table > tbody").empty();
          <?php } ?>
          final_total();
      });
    });*/

     $(".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';
         }
     });


  /*Warehouse*/
    $("#warehouse_id").on("change",function(){
      var warehouse_id=$(this).val();
      $(".items_table > tbody").empty();
      get_details(null,true);
      final_total();
    });
    /*Warehouse end*/

  //RIGHT SIT DIV:-> FILTER ITEM INTO THE ITEMS LIST
  function search_it(){
  
  /*var input = $("#search_it").val();
  var item_count=$(".search_div .search_item").length;
  var error_count=item_count;
  for(i=0; i<item_count; i++){
    console.log("item_count ->"+i+" =>"+$("#item_"+i).html());
    console.log($("#item_"+i).html().toUpperCase().indexOf(input.toUpperCase()));
    if($("#item_"+i).html().toUpperCase().indexOf(input.toUpperCase())>-1){
      console.log("found");
      $("#item_"+i).show();
      $("#item_parent_"+i).show();
    }
    else{
     console.log("not-found"); 
     $("#item_"+i).hide();
     $("#item_parent_"+i).hide();
     error_count--;
    }
    if(error_count==0){
      $(".error_div").show();
    }
    else{
      $(".error_div").hide();
    }
    
  }*/
  }




//LEFT SIDE: ON CLICK ITEM ADD TO INVOICE LIST
function addrow(id='',item_obj=''){


    var item_id = (item_obj=='') ? $('#div_'+id).attr('data-item-id') : item_obj.item_id; 

    //CHECK SAME ITEM ALREADY EXIST IN ITEMS TABLE 
    var item_check=check_same_item(item_id);
    if(!item_check){return false;}
    var rowcount        =$("#hidden_rowcount").val();//0,1,2...
    var item_name = (item_obj=='') ? $('#div_'+id).attr('data-item-name') : item_obj.item_name; 

    var stock   =(item_obj=='') ? $('#div_'+id).attr('data-item-available-qty') : item_obj.stock;
        stock     =(parseFloat(stock)).toFixed(2);

    var tax_type   =(item_obj=='') ? $('#div_'+id).attr('data-item-tax-type') : item_obj.tax_type;  
    var tax_id   =(item_obj=='') ? $('#div_'+id).attr('data-item-tax-id') : item_obj.tax_id;  
    var tax_value   =(item_obj=='') ? $('#div_'+id).attr('data-item-tax-value') : item_obj.tax;
    
    var tax_name   =(item_obj=='') ? $('#div_'+id).attr('data-item-tax-name'):item_obj.tax_name;  
    var tax_amt   =(item_obj=='') ? $('#div_'+id).attr('data-item-tax-amt') : item_obj.item_tax_amt; 
    //var purchase_price   =(item_obj=='') ? $('#div_'+id).attr('data-purchase_price') : item_obj.purchase_price; 
    var discount_type   =(item_obj=='') ? $('#div_'+id).attr('data-discount_type') :item_obj.discount_type; 
    var discount   =(item_obj=='') ? $('#div_'+id).attr('data-discount') : item_obj.discount; 
 
    
    var service_bit   =(item_obj=='') ? $('#div_'+id).attr('data-service_bit') : item_obj.service_bit; 
    //var gst_per         =$('#div_'+id).attr('data-item-tax-per');
    //var gst_amt         =$('#div_'+id).attr('data-item-gst-amt');

    var item_cost     =(item_obj=='') ? $('#div_'+id).attr('data-item-cost') : item_obj.purchase_price;  
    var sales_price     =(item_obj=='') ? $('#div_'+id).attr('data-item-sales-price') : item_obj.sales_price ; 
    var sales_price_temp=sales_price;
        sales_price     =to_Fixed(sales_price);

    var quantity        ='<div class="input-group input-group-sm"><span class="input-group-btn"><button onclick="decrement_qty('+item_id+','+rowcount+')" type="button" class="btn btn-default btn-flat compact-qty-btn"><i class="fa fa-minus text-danger"></i></button></span>';
        quantity       +='<input typ="text" value="'+format_qty(1)+'" class="form-control no-padding text-center min_width compact-qty-input" onchange="item_qty_input('+item_id+','+rowcount+')" id="item_qty_'+item_id+'" name="item_qty_'+item_id+'">';
        quantity       +='<span class="input-group-btn"><button onclick="increment_qty('+item_id+','+rowcount+')" type="button" class="btn btn-default btn-flat compact-qty-btn"><i class="fa fa-plus text-success"></i></button></span></div>';
    var sub_total       =(to_Fixed(1)*to_Fixed(sales_price));//Initial
    var remove_btn      ='<a class="fa fa-fw fa-trash-o text-red compact-remove-btn" onclick="removerow('+rowcount+')" title="Delete Item?"></a>';

    var str=' <tr id="row_'+rowcount+'" data-row="0" data-item-id='+item_id+'>';/*item id*/
        str+='<td id="td_'+rowcount+'_0"><a data-toggle="tooltip" title="Click to Change Tax" class="pointer" id="td_data_'+rowcount+'_0" onclick="show_sales_item_modal('+rowcount+')">'+ item_name     +'</a> <i onclick="show_sales_item_modal('+rowcount+')" class="fa fa-edit pointer"></i></td>';/* td_0_0 item name*/ 
        str+='<td id="td_'+rowcount+'_1">'+ stock +'</td>';/* td_0_1 item available qty*/
        str+='<td id="td_'+rowcount+'_2">'+ quantity      +'</td>';/* td_0_2 item available qty*/
            info='<input id="sales_price_'+rowcount+'" onblur="set_to_original('+rowcount+','+item_cost+')" onkeyup="update_price('+rowcount+','+item_cost+')" name="sales_price_'+rowcount+'" type="text" class="form-control no-padding min_width" value="'+sales_price+'">';
        str+='<td id="td_'+rowcount+'_3" class="text-right">'+ info   +'</td>';/* td_0_3 item sales price*/

        /*Discount*/
         info='<input data-toggle="tooltip" title="Click to Change" onclick="show_sales_item_modal('+rowcount+')" id="item_discount_'+rowcount+'" readonly name="item_discount_'+rowcount+'" type="text" class="form-control no-padding min_width pointer" value="0">';
         
        str+='<td id="td_'+rowcount+'_6" class="text-right">'+ info   +'</td>';

        /*Tax amt*/
        str+='<td id="td_'+rowcount+'_11"><input data-toggle="tooltip" title="Click to Change" id="td_data_'+rowcount+'_11" onclick="show_sales_item_modal('+rowcount+')" name="td_data_'+rowcount+'_11" type="text" class="form-control no-padding pointer min_width" readonly value="'+tax_amt+'"></td>';

        str+='<td id="td_'+rowcount+'_4" class="text-right"><input data-toggle="tooltip" title="Total" id="td_data_'+rowcount+'_4" name="td_data_'+rowcount+'_4" type="text" class="form-control no-padding pointer" readonly value="'+sub_total+'"></td>';/* td_0_4 item sub_total */
        str+='<td id="td_'+rowcount+'_5">'+ remove_btn    +'</td>';/* td_0_5 item gst_amt */

        str+='<input type="hidden" name="tr_item_id_'+rowcount+'" id="tr_item_id_'+rowcount+'" value="'+item_id+'">';
       // str+='<input type="hidden" id="tr_item_per_'+rowcount+'" name="tr_item_per_'+rowcount+'" value="'+gst_per+'">';
        str+='<input type="hidden" id="tr_sales_price_temp_'+rowcount+'" name="tr_sales_price_temp_'+rowcount+'" value="'+sales_price_temp+'">';
        str+='<input type="hidden" id="tr_tax_type_'+rowcount+'" name="tr_tax_type_'+rowcount+'" value="'+tax_type+'">';
        str+='<input type="hidden" id="tr_tax_id_'+rowcount+'" name="tr_tax_id_'+rowcount+'" value="'+tax_id+'">';
        str+='<input type="hidden" id="tr_tax_value_'+rowcount+'" name="tr_tax_value_'+rowcount+'" value="'+tax_value+'">';
        str+='<input type="hidden" id="description_'+rowcount+'" name="description_'+rowcount+'" value="">';
        str+='<input type="hidden" id="service_bit_'+rowcount+'" name="service_bit_'+rowcount+'" value="'+service_bit+'">';
        str+='<input id="item_discount_type_'+rowcount+'" name="item_discount_type_'+rowcount+'" type="hidden" value="'+discount_type+'">';
         str+='<input id="item_discount_input_'+rowcount+'" name="item_discount_input_'+rowcount+'" type="hidden" value="'+discount+'">';
        str+='</tr>';   

    //LEFT SIDE: ADD OR APPEND TO SALES INVOICE TERMINAL
    $('#pos-form-tbody').append(str);

    //LEFT SIDE: INCREMANT ROW COUNT
    $("#hidden_rowcount").val(parseFloat($("#hidden_rowcount").val())+1);
    failed.currentTime = 0;
    failed.play();
    //CALCULATE FINAL TOTAL AND OTHER OPERATIONS
    make_subtotal(item_id,rowcount);
  }

function update_price(row_id,item_cost){
  /*Input*/
  /*var sales_price=$("#sales_price_"+row_id).val();
  if(sales_price!='' || sales_price==0) {sales_price = parseFloat(sales_price); }

  Default set from item master
  var item_price=parseFloat($("#tr_sales_price_temp_"+row_id).val());

  if(sales_price<item_cost){
    //toastr["warning"]("Minimum Sales Price is "+item_cost);
    $("#sales_price_"+row_id).parent().addClass('has-error');
  }else{
    $("#sales_price_"+row_id).parent().removeClass('has-error');
  }*/

  make_subtotal($("#tr_item_id_"+row_id).val(),row_id);
}

function set_to_original(row_id,item_cost) {
  return true;
  /*Input*/
  var sales_price=$("#sales_price_"+row_id).val();
  if(sales_price!='' || sales_price==0) {sales_price = parseFloat(sales_price); }

  /*Default set from item master*/
  var item_price=parseFloat($("#tr_sales_price_temp_"+row_id).val());

  if(sales_price<item_cost){
    toastr["success"]("Default Price Set "+item_price);
    $("#sales_price_"+row_id).parent().removeClass('has-error');
    $("#sales_price_"+row_id).val(item_price);
  }
  make_subtotal($("#tr_item_id_"+row_id).val(),row_id);
}


//INCREMENT ITEM
function increment_qty(item_id,rowcount){
  var service_bit=$("#service_bit_"+rowcount).val();
  var item_qty=$("#item_qty_"+item_id).val();
  var stock=$("#td_"+rowcount+"_1").html();
  if(service_bit==1 || parseFloat(item_qty)<parseFloat(stock)){
    item_qty=parseFloat(item_qty)+1;
    $("#item_qty_"+item_id).val(format_qty(item_qty));
  }
  make_subtotal(item_id,rowcount);
}
//DECREMENT ITEM
function decrement_qty(item_id,rowcount){
  var item_qty=$("#item_qty_"+item_id).val();
  if(item_qty<=1){
    $("#item_qty_"+item_id).val(format_qty(1));
    return;
  }
  $("#item_qty_"+item_id).val(format_qty(parseFloat(item_qty)-1));
  make_subtotal(item_id,rowcount);
}
//LEFT SIDE: IF ITEM QTY CHANGED MANUALLY
function item_qty_input(item_id,rowcount){
  var item_qty=$("#item_qty_"+item_id).val();
  var service_bit=$("#service_bit_"+rowcount).val();
  var stock=$("#td_"+rowcount+"_1").html();

  if(service_bit!=1){
    if(stock==0){
      toastr["warning"]("item Not Available in stock!");
      //return;  
    }
    if(parseFloat(item_qty)>parseFloat(stock)){
      $("#item_qty_"+item_id).val(format_qty(stock));
      toastr["warning"]("Oops! You have only "+stock+" items in Stock");
     // return;
    }
    if(item_qty==0){
      $("#item_qty_"+item_id).val(format_qty(1));
      toastr["warning"]("You must have atlease one Quantity");
      //return; 
    }
    /*else{
      $("#item_qty_"+item_id).val(1);
      toastr["warning"]("You must have atlease one Quantity");
      return; 
    }*/
  }

  make_subtotal(item_id,rowcount);
}

function zero_stock(){
  toastr["error"]("Out of Stock!");
  return;
}
//LEFT SIDE: REMOVE ROW 
function removerow(id){//id=Rowid  
    $("#row_"+id).remove();
    failed.currentTime = 0;
    failed.play();
    final_total();
}

//MAKE SUBTOTAL


function make_subtotal(item_id,rowcount){
  set_tax_value(rowcount);

   //Find the Tax type and Tax amount
   var tax_type = $("#tr_tax_type_"+rowcount).val();
   var tax_amount = $("#td_data_"+rowcount+"_11").val();

  var sales_price     =$("#sales_price_"+rowcount).val();
  //var gst_per         =$("#tr_item_per_"+rowcount).val();
  var item_qty        =$("#item_qty_"+item_id).val();

  var tot_sales_price =parseFloat(item_qty)*parseFloat(sales_price);
  //var gst_amt=(tot_sales_price * gst_per)/100;

  var subtotal        =parseFloat(tot_sales_price);
  /*Discounr*/
  var discount_amt    =$("#item_discount_"+rowcount).val();

  subtotal = (tax_type=='Inclusive') ? subtotal : parseFloat(subtotal) + parseFloat(tax_amount);

  subtotal -= parseFloat(discount_amt);
  
  $("#td_data_"+rowcount+"_4").val(to_Fixed(subtotal));
  final_total();
}


function calulate_discount(discount_input,discount_type,total){
  discount_input = parseFloat(discount_input) || 0;
  total = parseFloat(total) || 0;
  
  if(discount_type=='in_percentage'){
    return parseFloat((total*discount_input)/100);
  }
  else{//in_fixed
    return parseFloat(discount_input);
  }
}
//LEFT SIDE: FINAL TOTAL


function final_total(){
  var total=0;
  var item_qty=0;
  var rowcount=$("#hidden_rowcount").val();
  var discount_input=parseFloat($("#discount_input").val()) || 0;
  var discount_type=$("#discount_type").val();

  if($(".items_table tr").length>1){
    for(i=0;i<rowcount;i++){
      if(document.getElementById('tr_item_id_'+i)){
      item_id=$("#tr_item_id_"+i).val();
      
      total=parseFloat(total)+parseFloat($("#td_data_"+i+"_4").val());
      item_qty=parseFloat(item_qty)+parseFloat($("#item_qty_"+item_id).val());
      item_qty = format_qty(item_qty);
      }
    }//for end
  }//items_table
  
  var discount_amt=0;
  if(total>0){
    var discount_amt=calulate_discount(discount_input,discount_type,total);//return value 
  }

  var subtotal = total-discount_amt;

  var coupon_amt = discount_coupon_tot(subtotal);
      subtotal -=coupon_amt;
    
  set_total(item_qty,total,discount_amt,subtotal);
}
function set_total(tot_qty=0, tot_amt=0, tot_disc=0, tot_grand=0){
  $(".tot_qty   ").html(tot_qty);
  $(".tot_amt   ").html(to_Fixed(tot_amt));
  $(".tot_disc  ").html(to_Fixed(tot_disc));
  $(".tot_grand ").html(to_Fixed(round_off(tot_grand)));
}

//LEFT SIDE: FINAL TOTAL
function adjust_payments(){
  var total=0;
  var item_qty=parseFloat(0);
  var rowcount=$("#hidden_rowcount").val();
  var discount_input=parseFloat($("#discount_input").val()) || 0;
  var discount_type=$("#discount_type").val();

  if($(".items_table tr").length>1){
    for(i=0;i<rowcount;i++){
      if(document.getElementById('tr_item_id_'+i)){
        total=parseFloat(total)+parseFloat($("#td_data_"+i+"_4").val());
        item_id=$("#tr_item_id_"+i).val();

        var row_wise_item_qty = parseFloat($("#item_qty_"+item_id).val()) || 0;
        item_qty += row_wise_item_qty;
      }
    }//for end
  }//items_table

  //Find customers payment
  var payments_row = parseInt($("#payment_row_count").val()) || 1;
  var paid_amount = parseFloat(0);
  
  for (var i = 1; i <= payments_row; i++) {
    if(document.getElementById("amount_"+i)){
      var amount = parseFloat($("#amount_"+i).val()) || 0;
      paid_amount += amount;
    }
  }
  
  //Calculate discount
  var discount_amt = calulate_discount(discount_input, discount_type, total);

  var change_return = 0;
  var subtotal = total - discount_amt;
  var coupon_amt = discount_coupon_tot(subtotal);
  subtotal -= coupon_amt;

  var balance = subtotal - paid_amount;

  if(balance < 0){
    change_return = Math.abs(parseFloat(balance));
    balance = 0;
  }
  
  // Update display values with proper formatting
  $(".sales_div_tot_qty").html(format_qty(item_qty));
  $(".sales_div_tot_amt").html(to_Fixed(total));
  $(".sales_div_tot_discount").html(to_Fixed(discount_amt)); 
  $(".coupon_discount_div_amt").html(to_Fixed(coupon_amt)); 
  $("#coupon_discount_amt").val(coupon_amt); 
  $(".sales_div_tot_payble").html(to_Fixed(subtotal)); 
  $(".sales_div_tot_paid").html(to_Fixed(paid_amount));
  $(".sales_div_tot_balance").html(to_Fixed(balance)); 
  $(".sales_div_change_return").html(to_Fixed(change_return)); 
}

$(document).ready(function(){
  get_coupon_details();
});
function check_same_item(item_id){

  if($(".items_table tr").length>1){
    var rowcount=$("#hidden_rowcount").val();
    for(i=0;i<=rowcount;i++){
            if($("#tr_item_id_"+i).val()==item_id){
              increment_qty(item_id,i);
              failed.currentTime = 0;
              failed.play();
              return false;
            }
      }//end for
  }
  return true;
}




$(document).ready(function(){
  
  $("#store_id").trigger('change');

  var customer_id = "<?= (!empty($customer_id)) ? $customer_id : '';  ?>";

  autoLoadFirstCustomer(customer_id);

  //FIRST TIME: LOAD
  //get_details();

  // Optimized table height calculation for compact design
  var viewport_height = $(window).height();
  var content_wrapper_height = $(".content-wrapper").height();
  var navbar_height = $(".main-header").height() || 50;
  var available_height = viewport_height - navbar_height - 100; // 100px buffer
  
  var optimal_table_height = Math.min(400, Math.max(300, available_height * 0.4));
  
  $(".items_table_container").css({
    "max-height": optimal_table_height + "px",
    "min-height": (optimal_table_height - 50) + "px"
  });
  
  // Right panel optimization - Increase height significantly by 10%
  var right_panel_height = Math.min(viewport_height - 160, Math.max(600, available_height * 0.99));
  $("#items_search_list").css({
    "max-height": right_panel_height + "px",
    "height": "auto"
  });

  // Responsive adjustments
  $(window).resize(function() {
    var new_viewport = $(window).height();
    var new_available = new_viewport - 150;
    var new_table_height = Math.min(400, Math.max(300, new_available * 0.4));
    var new_panel_height = Math.min(new_viewport - 160, Math.max(600, new_available * 0.99));
    
    $(".items_table_container").css("max-height", new_table_height + "px");
    $("#items_search_list").css("max-height", new_panel_height + "px");
  });

  



  //FIRST TIME: SET TOTAL ZERO
  set_total();

  //RIGHT DIV: FILTER INPUT BOX
 /* $("#search_it").on("keyup",function(){
    search_it();
  });*/

  //CATEGORY WISE ITEM FETCH FROM SERVER
  var show_only_searched=true;
  $("#category_id,#brand_id").on("change",function () {
      get_details(null,show_only_searched);
  });

  //DISCOUNT UPDATE
  $(".discount_update").on("click",function () {
      final_total();
      $('#discount-modal').modal('toggle');    
  });

  $("#item_name").on("keyup",function () {
      get_details(null,show_only_searched);
  });

  //RIGHT SIDE: CLEAR SEARCH BOX
 /* $(".show_all").on("click",function(){
    $("#search_it").val('').trigger("keyup");
    $("#category_id").val('').trigger("change");
  });*/

  //Reset Category & brand
  $(".reset_categories").on("click",function(){
      $("#category_id").val('').trigger("change");
  });
  $(".reset_brands").on("click",function(){
      $("#brand_id").val('').trigger("change");
  });
  $(".reset_item_name").on("click",function(){
      $("#item_name").val('');
      $("#brand_id").val('').trigger("change");
  });
  
  // Prevent disabled buttons from being clicked in edit mode
  $(document).on('click', '.disabled', function(e) {
      e.preventDefault();
      e.stopPropagation();
      toastr["warning"]("This function is disabled in edit mode. Use Multiple Payments instead.");
      return false;
  });
  
  //UPDATE PROCESS START
 <?php if(isset($sales_id) && !empty($sales_id)){ ?>
    $("#store_id").attr('readonly',true);
    $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
    
    // Disable buttons in edit mode except multiple payment
    $("#hold_invoice, #show_cash_modal, #pay_all").prop('disabled', true).addClass('disabled');
    
    $.get("<?php echo $base_url ?>pos/fetch_sales/<?php echo $sales_id ?>",{},function(result){
      console.log(result);

      result=result.split("<<<###>>>");
      $('#pos-form-tbody').append(result[0]);
      $('#discount_input').val(result[1]);
      $('#discount_type').val(result[2]);

      $('#invoice_terms').text(result[7]);
      /*if(store_module){
        $('#store_id').val(result[4]).select2();
      }
      else{*/
        $('#store_id').val(result[4]);
      /*}*/
      console.log("warehouse = "+result[5]);
      if(warehouse_module){
        $('#warehouse_id').val(result[5]).select2();
      }
      else{
        $('#warehouse_id').val(result[5]);
      }

      //$('#customer_id').val(result[3]).select2();
      //$("#customer_id").trigger("change");
      
      // Load customer if available
      if(result[3] && result[3] != ''){
        console.log("Loading customer ID: " + result[3]);
        setTimeout(function() {
          autoLoadFirstCustomer(result[3]);
        }, 500); // Small delay to ensure DOM is ready
      }
      
      
      $("#hidden_rowcount").val(parseInt($(".items_table tr").length)-1);
      final_total();
      get_details();
      $(".overlay").remove();
      
      if(result[5]==1){
        $( "#binvoice" ).prop( "checked", true );
        $('#binvoice').parent('div').addClass('checked');
      }
    });
      //DISABLE THE HOLD BUTTON ONLY - Keep other buttons working for edit
      $("#hold_invoice").attr('disabled',true);

 <?php } else{?>
  get_details();
 <?php } ?>
  //UPDATE PROCESS END

  // Button Event Handlers for POS actions
  $("#pay_all").off('click').on("click",function(){
    var was_fullscreen = fullscreen_enabled;
    
    // Store fullscreen state before operation
    localStorage.setItem('pos_fullscreen_state', was_fullscreen);
    
    save(print=true,pay_all=true);
    
    // For print operations, be very aggressive about maintaining fullscreen
    if (was_fullscreen) {
      // Start monitoring immediately
      var aggressiveRestore = setInterval(function() {
        if (!fullscreen_enabled) {
          enterFullscreen();
        }
      }, 100); // Check every 100ms
      
      // Stop after 1 minute
      setTimeout(function() {
        clearInterval(aggressiveRestore);
      }, 60000);
    }
  });

  // Removed conflicting handlers - using pos.js handlers instead

});//ready() end

// Helper functions for POS
function uncheck_allow_tot_advance(){
  //verify is checked ?
  if($("#allow_tot_advance").is(':checked')){
    $("#click_to_uncheck").trigger("click");
  }
}

function remove_row(id){
  $(".payments_div_"+id).html('');
  failed.currentTime = 0;
  failed.play();
  adjust_payments();
}

function get_float_type_data(selector) {
  var value = parseFloat($(selector).val());
  return isNaN(value) ? 0 : value;
}

function get_id_value(id){
  return $("#"+id).val();
}

// XSS Validation function
function xss_validation(data) {
  // Basic XSS validation - can be enhanced as needed
  return true; // For now, always return true
}

function hold_invoice_list(){
  var base_url=$("#base_url").val();
  $.post(base_url+"pos/hold_invoice_list",{},function(result){
    var data = jQuery.parseJSON(result)
    $("#hold_invoice_list").html('').html(data['result']);
    $(".hold_invoice_list_count").html('').html(data['tot_count']);
  });
}



//DATEPICKER INITIALIZATION
$('#order_date,#delivery_date,#cheque_date').datepicker({
      autoclose: true,
      format: 'dd-mm-yyyy',
      todayHighlight: true
    });
    $('#customer_dob,#birthday_person_dob').datepicker({
      calendarWeeks: true,
      todayHighlight: true,
      autoclose: true,
      format: 'dd-mm-yyyy',
      startView: 2
    });
    
    //Datemask dd-mm-yyyy
    //$("#customer_dob,#birthday_person_dob").inputmask("dd-mm-yyyy", {"placeholder": "dd-mm-yyyy"});

    //Timepicker
    /*$('.timepicker').timepicker({
      showInputs: false,
    });*/

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

      //Find the item details
      var item_name = $("#td_data_"+row_id+"_0").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_row_id").val(row_id);
      $("#popup_description").val(description);
    }

    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'));

      /*Discounr*/
      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);
      $("#description_"+row_id).val(description);
      $("#tr_tax_value_"+row_id).val(tax);//%
      //$("#td_data_"+row_id+"_12").html(tax_type+" "+tax_name);
      
      var item_id=$("#tr_item_id_"+row_id).val();
      make_subtotal(item_id,row_id);
      //calculate_tax(row_id);
      $('#sales_item').modal('toggle');
    }
    function set_tax_value(row_id){
      //get the sales price of the item
      var tax_type = $("#tr_tax_type_"+row_id).val();
      var tax = $("#tr_tax_value_"+row_id).val(); //%
      var item_id=$("#tr_item_id_"+row_id).val();
      var qty=($("#item_qty_"+item_id).val());
          qty = (isNaN(qty)) ? 0 :qty;

      var sales_price = parseFloat($("#sales_price_"+row_id).val());
          sales_price = (isNaN(sales_price)) ? 0 :sales_price;
          sales_price = sales_price * qty;

      /*Discount*/
      var item_discount_type = $("#item_discount_type_"+row_id).val();
      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') ? ((sales_price) * item_discount_input)/100 : (item_discount_input*qty);
     
      sales_price-=parseFloat(discount_amt);

      var tax_amount = (tax_type=='Inclusive') ? calculate_inclusive(sales_price,tax) : calculate_exclusive(sales_price,tax);
      
      $("#item_discount_"+row_id).val(to_Fixed(discount_amt));
      $("#td_data_"+row_id+"_11").val(to_Fixed(tax_amount));
    }
    //Sale Items Modal Operations End

</script>
<script>
    // Initialize custom checkboxes (modern style)
    $('.modern-checkbox').on('change', function() {
        var $label = $(this).closest('.modern-checkbox-label');
        var $checkmark = $(this).siblings('.modern-checkmark');
        var $text = $(this).siblings('.checkbox-text');
        
        if ($(this).is(':checked')) {
            $checkmark.addClass('checked');
            $text.addClass('checked');
            $label.addClass('active');
        } else {
            $checkmark.removeClass('checked');
            $text.removeClass('checked');
            $label.removeClass('active');
        }
    });

    // Trigger change event for initially checked boxes
    $('.modern-checkbox:checked').trigger('change');

    // Traditional iCheck for other checkboxes
    $('input:not(.modern-checkbox)').iCheck({
      checkboxClass: 'icheckbox_square-blue',
      radioClass: 'iradio_square-blue',
      increaseArea: '20%' // optional
    });
</script>
<script type="text/javascript">
  shortcut.add("Alt+m",function(e) {
        e.preventDefault();
        $(".show_payments_modal").trigger('click');
    },{
        'type':'keydown',
        'propagate':true,
        'target':document
      });

  shortcut.add("Alt+h",function(e) {
        e.preventDefault();
        $("#hold_invoice").trigger('click');
    },{
        'type':'keydown',
        'propagate':true,
        'target':document
      });
  shortcut.add("Alt+c",function(e) {
        e.preventDefault();
        $(".Alt_c").trigger('click');
    },{
        'type':'keydown',
        'propagate':true,
        'target':document
      });
  shortcut.add("Alt+a",function(e) {
        e.preventDefault();
        $(".Alt_a").trigger('click');
    },{
        'type':'keydown',
        'propagate':true,
        'target':document
      });
  shortcut.add("Alt+e",function(e) {
        e.preventDefault();
        $("#expense_btn").trigger('click');
    },{
        'type':'keydown',
        'propagate':true,
        'target':document
      });
  shortcut.add("Alt+s",function(e) {
        e.preventDefault();
        $("#summary_btn").trigger('click');
    },{
        'type':'keydown',
        'propagate':true,
        'target':document
      });
  shortcut.add("Alt+t",function(e) {
        e.preventDefault();
        $("#stock_adj_btn").trigger('click');
    },{
        'type':'keydown',
        'propagate':true,
        'target':document
      });
  shortcut.add("Alt+p",function(e) {
        e.preventDefault();
        if($("#daily-summary-modal").hasClass('in')) {
            $("#print-summary").trigger('click');
        }
    },{
        'type':'keydown',
        'propagate':true,
        'target':document
      });
</script>

<script>

//Reset Tooltip
function reset_tooltip() {
  $('[data-toggle="tooltip"]').tooltip("destroy");
  $('[data-toggle="tooltip"]').tooltip(); // re-enabling 
}
$('.search_div').on('scroll', function() {
    if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {

      if($(".scroll_or_not").val()=="true"){

        //Scroll Restriction Enabled
        $(".scroll_or_not").val("false");
        //Ajax Loader
        $('.ajax-load').show();

        setTimeout(function() {
          //Ajax Request
          load_next_details();  
          //Scroll Restriction Disabled
          $(".scroll_or_not").val("true");
          //Ajax Loader End
          $('.ajax-load').hide();    
        }, 1000);
        
        
      }
      
    }
});

function load_next_details(){
  var last_id = $(".item_box:last").attr("data-item-id");
  get_details(last_id);
}



function get_details(last_id='',show_only_searched=false){

  warehouse_id = $("#warehouse_id").val();

  $.ajax({
      url: '<?php echo $base_url; ?>pos/get_details',
      type: "post",
      data:{
        last_id       : (!show_only_searched) ? last_id : '',
        customer_id   : $("#customer_id").val(),
        id            : $("#category_id").val(),
        store_id      : $("#store_id").val(),
        warehouse_id  : $("#warehouse_id").val(),
        item_name     : $("#item_name").val(),
        //search_it  : $("#search_it").val(),
        brand_id  : $("#brand_id").val(),

      },
      beforeSend: function(){
          $('.ajax-load').show();
      }
  }).done(function(data){
      $('.ajax-load').hide();
      
      if(data=='') {
        $(".error_div").show();
      }
      else{
        $(".error_div").hide();
      }


      if(show_only_searched){
        $(".search_div").html('');
      }
      $(".search_div").append(data);
      reset_tooltip();
  }).fail(function(jqXHR, ajaxOptions, thrownError){
      alert('server not responding...');
  });
}

// Modal Compact Enhancement Script
$(document).ready(function() {
    // Function to adjust modal height based on viewport
    function adjustModalHeight() {
        var viewportHeight = $(window).height();
        var maxModalHeight = Math.floor(viewportHeight * 0.9);
        
        $('.modal-content').css('max-height', maxModalHeight + 'px');
        $('.modal-body').css('max-height', Math.floor(maxModalHeight * 0.7) + 'px');
    }
    
    // Adjust on modal show
    $('.modal').on('show.bs.modal', function() {
        adjustModalHeight();
    });
    
    // Adjust on window resize
    $(window).resize(function() {
        if ($('.modal').hasClass('in')) {
            adjustModalHeight();
        }
    });
    
    // Initialize Select2 with compact settings for modals
    $('.modal').on('shown.bs.modal', function() {
        $(this).find('select').select2({
            dropdownParent: $(this),
            minimumResultsForSearch: 5,
            placeholder: "Select...",
            width: '100%'
        });
    });
    
    // Modern button styling - add hover effects and maintain functionality
    $('.modern-btn').on('mouseenter', function() {
        if (!$(this).hasClass('disabled')) {
            $(this).addClass('btn-hover');
        }
    }).on('mouseleave', function() {
        $(this).removeClass('btn-hover');
    });

    // Ensure modern buttons inherit original functionality
    $('.btn-hold').addClass('btnhold');
    $('.btn-multiple').addClass('btnhold');
    $('.btn-cash').addClass('btnhold');
    $('.btn-pay-all').addClass('btnhold');
    
    // Auto-focus first input in modals
    $('.modal').on('shown.bs.modal', function() {
        $(this).find('input[type="text"]:visible:first').focus();
    });
    
    // Customer Action Button functionality
    $("#customer_action_btn").on("click", function() {
        var customer_id = $("#customer_id").val();
        if (!customer_id || customer_id == '') {
            toastr["warning"]("Please select a customer first!");
            return;
        }
        showCustomerActionModal(customer_id);
    });
    
    // Show/hide customer action button based on customer selection
    $("#customer_id").on("change", function() {
        var customer_id = $(this).val();
        if (customer_id && customer_id != '') {
            $("#customer_action_btn").show();
        } else {
            $("#customer_action_btn").hide();
        }
    });
    
    // Stock Adjustment Button functionality
    $("#stock_adj_btn").on("click", function() {
        var base_url = $("#base_url").val();
        var stock_adj_url = base_url + "stock_adjustment/add";
        window.open(stock_adj_url, '_blank');
    });
});

// Customer Action Modal Function
function showCustomerActionModal(customer_id) {
    var modal_content = `
        <div class="modal fade customer-action-modal" id="customer_action_modal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-sm" role="document">
                <div class="modal-content">
                    <div class="modal-header bg-primary">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title"><i class="fa fa-user"></i> Customer Actions</h4>
                    </div>
                    <div class="modal-body" style="padding: 0;">
                        <div class="list-group" style="margin-bottom: 0;">
                            <a href="javascript:void(0)" onclick="pay_now_pos(${customer_id})" class="list-group-item">
                                <i class="fa fa-money text-green"></i> Receive Due Payments
                            </a>
                            <a href="javascript:void(0)" onclick="pay_return_due_pos(${customer_id})" class="list-group-item">
                                <i class="fa fa-money text-orange"></i> Pay Return Due
                            </a>
                            <a href="javascript:void(0)" onclick="view_payments_pos(${customer_id})" class="list-group-item">
                                <i class="fa fa-list text-blue"></i> View Payments
                            </a>
                            <a href="${base_url}customers/update/${customer_id}" target="_blank" class="list-group-item">
                                <i class="fa fa-edit text-purple"></i> Edit Customer
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // Remove existing modal if any
    $("#customer_action_modal").remove();
    
    // Append new modal to body
    $("body").append(modal_content);
    
    // Show modal
    $("#customer_action_modal").modal('show');
}

// Customer Action Functions for POS
function pay_now_pos(customer_id) {
    $("#customer_action_modal").modal('hide');
    pay_now(customer_id);  // Use existing function from customers.js
    
    // Override the save_payment function to refresh customer data after payment
    window.original_save_payment = window.save_payment;
    window.save_payment = function(cust_id) {
        var base_url = $("#base_url").val();
        var flag = true;
        
        function check_field(id) {
            if (!$("#" + id).val()) {
                $('#' + id + '_msg').fadeIn(200).show().html('Required Field').addClass('required');
                flag = false;
            } else {
                $('#' + id + '_msg').fadeOut(200).hide();
            }
        }
        
        check_field("amount");
        check_field("payment_date");
        
        var payment_date = $("#payment_date").val();
        var amount = $("#amount").val();
        var payment_type = $("#payment_type").val();
        var payment_note = $("#payment_note").val();
        var account_id = $("#account_id").val();
        
        if (amount == 0) {
            toastr["error"]("Please Enter Valid Amount!");
            return false;
        }
        
        if (amount > parseFloat($("#amount").attr('data-due-amt'))) {
            toastr["error"]("Entered Amount Should not be Greater than Due Amount!");
            return false;
        }
        
        $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
        $(".payment_save").attr('disabled', true);
        
        $.post(base_url + 'customers/save_payment', {
            account_id: account_id,
            customer_id: cust_id,
            payment_type: payment_type,
            amount: amount,
            payment_date: payment_date,
            payment_note: payment_note
        }, function(result) {
            if (result == "success") {
                $('#pay_now').modal('hide');
                toastr["success"]("Payment Recorded Successfully!");
                // Update customer due amount in POS
                $("#customer_id").trigger('change');
                // Restore original function
                window.save_payment = window.original_save_payment;
            } else if (result == "failed") {
                toastr["error"]("Sorry! Failed to save Record.Try again!");
            } else {
                toastr["error"](result);
            }
            $(".payment_save").attr('disabled', false);
            $(".overlay").remove();
        });
    };
}

function pay_return_due_pos(customer_id) {
    $("#customer_action_modal").modal('hide');
    pay_return_due(customer_id);  // Use existing function from customers.js
    
    // Override the save_return_due_payment function to refresh customer data after payment
    window.original_save_return_due_payment = window.save_return_due_payment;
    window.save_return_due_payment = function(cust_id) {
        var base_url = $("#base_url").val();
        var flag = true;
        
        function check_field(id) {
            if (!$("#" + id).val()) {
                $('#' + id + '_msg').fadeIn(200).show().html('Required Field').addClass('required');
                flag = false;
            } else {
                $('#' + id + '_msgs').fadeOut(200).hide();
            }
        }
        
        check_field("return_due_amount");
        check_field("return_due_payment_date");
        
        var payment_date = $("#return_due_payment_date").val();
        var amount = $("#return_due_amount").val();
        var payment_type = $("#return_due_payment_type").val();
        var payment_note = $("#return_due_payment_note").val();
        var account_id = $("#account_id").val();
        
        if (amount == 0) {
            toastr["error"]("Please Enter Valid Amount!");
            return false;
        }
        
        if (amount > parseFloat($("#return_due_amount").attr('data-due-amt'))) {
            toastr["error"]("Entered Amount Should not be Greater than Due Amount!");
            return false;
        }
        
        $(".box").append('<div class="overlay"><i class="fa fa-refresh fa-spin"></i></div>');
        $(".return_due_payment_save").attr('disabled', true);
        
        $.post(base_url + 'customers/save_return_due_payment', {
            account_id: account_id,
            customer_id: cust_id,
            payment_type: payment_type,
            amount: amount,
            payment_date: payment_date,
            payment_note: payment_note
        }, function(result) {
            if (result == "success") {
                $('#pay_return_due').modal('hide');
                toastr["success"]("Payment Recorded Successfully!");
                // Update customer due amount in POS
                $("#customer_id").trigger('change');
                // Restore original function
                window.save_return_due_payment = window.original_save_return_due_payment;
            } else if (result == "failed") {
                toastr["error"]("Sorry! Failed to save Record.Try again!");
            } else {
                toastr["error"](result);
            }
            $(".return_due_payment_save").attr('disabled', false);
            $(".overlay").remove();
        });
    };
}

function view_payments_pos(customer_id) {
    $("#customer_action_modal").modal('hide');
    view_payments(customer_id);  // Use existing function from customers.js
}

// Expense Modal Functions
$(document).ready(function() {
    // Initialize datepicker for expense modal
    $('#expense-modal').on('shown.bs.modal', function() {
        $('#modal_expense_date').datepicker({
            autoclose: true,
            format: 'dd-mm-yyyy',
            todayHighlight: true
        });
        
        // Initialize select2 for dropdowns
        $('#modal_category_id, #modal_payment_type, #modal_account_id').select2({
            dropdownParent: $('#expense-modal'),
            width: '100%'
        });
        
        // Reset form when modal opens
        clearExpenseForm();
        
        // Auto-focus on first field
        setTimeout(function() {
            $('#modal_category_id').select2('open');
        }, 300);
    });
    
    // Save expense functionality
    $('.add_expense').on('click', function() {
        saveExpense();
    });
    
    // Clear form when modal is hidden
    $('#expense-modal').on('hidden.bs.modal', function() {
        clearExpenseForm();
    });
});

function clearExpenseForm() {
    $('#expense-form-modal')[0].reset();
    $('#modal_expense_date').val('<?php echo show_date(date("d-m-Y")); ?>');
    $('#modal_category_id, #modal_payment_type, #modal_account_id').val('').trigger('change');
    $('.text-danger').hide();
}

// Daily Summary Modal Functions
$(document).ready(function() {
    // Load summary when modal is shown
    $('#daily-summary-modal').on('shown.bs.modal', function() {
        loadDailySummary();
    });
    
    // Refresh summary functionality
    $('#refresh-summary').on('click', function() {
        loadDailySummary();
    });
    
    // Print summary functionality
    $('#print-summary').on('click', function() {
        printDailySummary();
    });
});

function printDailySummary() {
    var base_url = $("#base_url").val();
    
    // Open print view in new window
    var printWindow = window.open(
        base_url + 'pos/print_daily_summary?autoprint=1', 
        'print_summary', 
        'width=300,height=600,scrollbars=yes,resizable=yes'
    );
    
    if (printWindow) {
        printWindow.focus();
    } else {
        toastr["error"]("Please allow popups to print the summary!");
    }
}

function loadDailySummary() {
    var base_url = $("#base_url").val();
    
    // Show loading
    $('#summary-loading').show();
    $('#summary-content').hide();
    
    $.ajax({
        url: base_url + 'pos/get_daily_summary',
        type: 'POST',
        dataType: 'json',
        success: function(data) {
            populateSummaryData(data);
            $('#summary-loading').hide();
            $('#summary-content').show();
        },
        error: function() {
            toastr["error"]("Failed to load summary data!");
            $('#summary-loading').hide();
            $('#daily-summary-modal').modal('hide');
        }
    });
}

function populateSummaryData(data) {
    // Set summary date in modern format
    var summaryDate = new Date(data.date);
    var dateOptions = { 
        weekday: 'long', 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric' 
    };
    $('#summary-date').text(summaryDate.toLocaleDateString('en-US', dateOptions));
    
    // Sales data
    $('#total-sales-count').text(data.sales.count);
    $('#total-sales-amount').text(formatCurrency(data.sales.amount));
    $('#summary-total-sales').text(formatCurrency(data.sales.amount));
    
    // Expenses data
    $('#total-expense-count').text(data.expenses.count);
    $('#total-expense-amount').text(formatCurrency(data.expenses.amount));
    $('#summary-expenses').text(formatCurrency(data.expenses.amount));
    
    // Balance calculation
    var balance = data.balance;
    $('#net-balance').text(formatCurrency(balance));
    
    // Update balance box color based on positive/negative
    var balanceBox = $('#balance-box');
    balanceBox.removeClass('bg-green bg-red bg-yellow');
    if (balance > 0) {
        balanceBox.addClass('bg-green');
        $('#balance-status').text('Profit');
    } else if (balance < 0) {
        balanceBox.addClass('bg-red');
        $('#balance-status').text('Loss');
    } else {
        balanceBox.addClass('bg-yellow');
        $('#balance-status').text('Break Even');
    }
    
    // Collection summary
    $('#summary-collected').text(formatCurrency(data.sales.paid_amount));
    $('#summary-pending').text(formatCurrency(data.sales.due_amount));
    
    // Customer dues
    $('#customer-count').text(data.customer_dues.customers_count);
    $('#customer-dues').text(formatCurrency(data.customer_dues.total_amount));
    
    // Payment modes
    var paymentModesList = $('#payment-modes-list');
    paymentModesList.empty();
    
    if (data.payment_modes.length > 0) {
        data.payment_modes.forEach(function(mode) {
            var percentage = (data.sales.paid_amount > 0) ? 
                ((mode.payment_amount / data.sales.paid_amount) * 100).toFixed(1) : 0;
            
            var modeHtml = `
                <div style="margin-bottom: 12px; padding: 12px 0; border-bottom: 2px solid #f8f9fa; text-align: center;">
                    <div style="font-weight: 700; font-size: 15px; color: #495057; margin-bottom: 5px;">${mode.payment_type}</div>
                    <div style="font-size: 18px; font-weight: 700; color: #28a745; margin-bottom: 3px;">${formatCurrency(mode.payment_amount)}</div>
                    <div style="font-size: 11px; color: #6c757d; font-weight: 500;">${mode.payment_count} transactions • ${percentage}%</div>
                </div>
            `;
            paymentModesList.append(modeHtml);
        });
    } else {
        paymentModesList.html(`
            <div class="text-center" style="padding: 30px; color: #6c757d;">
                <i class="fa fa-info-circle" style="font-size: 32px; margin-bottom: 12px; color: #17a2b8;"></i>
                <div style="font-size: 14px; font-weight: 600;">No payment transactions today</div>
            </div>
        `);
    }
    
    // Add summary message
    var totalTransactions = parseInt(data.sales.count) + parseInt(data.expenses.count);
    if (totalTransactions === 0) {
        toastr["info"]("No sales or expenses recorded for today");
    }
}

function formatCurrency(amount) {
    var currency_symbol = '<?= $CI->currency(); ?>';
    return currency_symbol + parseFloat(amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}

function formatDate(dateString) {
    var date = new Date(dateString);
    var options = { year: 'numeric', month: 'long', day: 'numeric' };
    return date.toLocaleDateString('en-US', options);
}

function saveExpense() {
    var base_url = $("#base_url").val();
    var flag = true;
    
    // Clear previous error messages
    $('.text-danger').hide();
    
    // Validate required fields
    function check_field(id, message) {
        if (!$("#" + id).val()) {
            $('#' + id + '_msg').fadeIn(200).show().html(message || 'Required Field').addClass('required');
            flag = false;
        } else {
            $('#' + id + '_msg').fadeOut(200).hide();
        }
    }
    
    check_field("modal_expense_date", "Expense Date is required");
    check_field("modal_category_id", "Category is required");
    check_field("modal_expense_for", "Expense For is required");
    check_field("modal_expense_amt", "Amount is required");
    check_field("modal_payment_type", "Payment Type is required");
    
    // Validate amount
    var amount = parseFloat($("#modal_expense_amt").val());
    if ($("#modal_expense_amt").val() && (isNaN(amount) || amount <= 0)) {
        $("#modal_expense_amt_msg").fadeIn(200).show().html('Please enter valid amount').addClass('required');
        flag = false;
    }
    
    if (!flag) {
        toastr["error"]("Please fill all required fields correctly!");
        return false;
    }
    
    // Show loading
    $(".add_expense").attr('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');
    
    // Prepare data
    var formData = {
        expense_date: $("#modal_expense_date").val(),
        category_id: $("#modal_category_id").val(),
        expense_for: $("#modal_expense_for").val(),
        expense_amt: $("#modal_expense_amt").val(),
        payment_type: $("#modal_payment_type").val(),
        account_id: $("#modal_account_id").val(),
        reference_no: $("#modal_reference_no").val(),
        note: $("#modal_note").val(),
        store_id: $("#modal_store_id").val()
    };
    
    // Add CSRF token
    formData[$('input[name="<?php echo $this->security->get_csrf_token_name();?>"]').attr('name')] = $('input[name="<?php echo $this->security->get_csrf_token_name();?>"]').val();
    
    // Save expense
    $.post(base_url + 'expense/pos_expense', formData, function(result) {
        if (result == "success") {
            $('#expense-modal').modal('hide');
            toastr["success"]("Expense Added Successfully!");
        } else if (result == "failed") {
            toastr["error"]("Sorry! Failed to save Record. Try again!");
        } else if (result == "insufficient_permissions") {
            toastr["error"]("You don't have permission to add expenses!");
        } else {
            toastr["error"](result);
        }
    }).fail(function() {
        toastr["error"]("Server error! Please try again.");
    }).always(function() {
        $(".add_expense").attr('disabled', false).html('Save Expense');
    });
}


</script> 
</body>
</html>
