<?php
// No session_start or header redirects here, as this will be included in pos.php
require 'db.php'; // DB connection
?>
<!-- POS Settings Offcanvas Sidebar -->
<div class="offcanvas offcanvas-end" tabindex="-1" id="posSettingsSidebar" aria-labelledby="posSettingsSidebarLabel">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title" id="posSettingsSidebarLabel">POS Settings</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body">
    <p><strong>Username:</strong> <?= htmlspecialchars($_SESSION['username'] ?? 'User') ?></p>
    <p><strong>Role:</strong> <?= htmlspecialchars($_SESSION['role_name'] ?? 'Staff') ?></p>
    <hr>
    <button class="btn btn-danger w-100 mb-3" data-bs-toggle="modal" data-bs-target="#closeShiftModal">
      <i data-feather="lock"></i> Close Shift
    </button>
    <a href="sale_return_search.php" class="btn btn-warning w-100 mb-3">
      <i data-feather="rotate-ccw"></i> Process Sale Return
    </a>
    <!-- Add more POS settings actions here as needed -->
  </div>
</div>

<!-- Close Shift Modal -->
<div class="modal fade" id="closeShiftModal" tabindex="-1" aria-labelledby="closeShiftModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form id="closeShiftForm">
      <div class="modal-content">
        <div class="modal-header bg-danger text-white">
          <h5 class="modal-title" id="closeShiftModalLabel">Close Shift</h5>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <label for="closing_cash" class="form-label">Enter Closing Cash:</label>
          <input type="number" name="closing_cash" class="form-control" id="closing_cash" required min="0" step="0.01">
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-danger w-100">Confirm Close</button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- Shift Summary Modal -->
<div class="modal fade" id="shiftSummaryModal" tabindex="-1" aria-labelledby="shiftSummaryModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="shiftSummaryModalLabel">Shift Summary</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div id="shiftSummaryContent">
          <!-- Content will be loaded here -->
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="printShiftSummary">
          <i data-feather="printer"></i> Print Summary
        </button>
        <button type="button" class="btn btn-success" id="confirmShiftClose">
          <i data-feather="check"></i> Confirm Close
        </button>
      </div>
    </div>
  </div>
</div>
<script>
  feather.replace();

  // Global variables for shift data
  let currentShiftData = null;
  let currentClosingCash = 0;

  document.getElementById('closeShiftForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    currentClosingCash = parseFloat(formData.get('closing_cash'));

    // First check for hold orders
    fetch('ajax/check_hold_orders.php')
      .then(res => res.json())
      .then(data => {
        console.log('Hold orders check response:', data);
        
        if (data.status === 'error') {
          // Show hold orders warning and prevent shift closing
          Swal.fire({
            icon: 'warning',
            title: 'Hold Orders Found',
            html: data.message + '<br><br><strong>Please process all hold orders before closing the shift.</strong>',
            confirmButtonColor: '#3085d6',
            confirmButtonText: 'OK'
          });
          return; // Stop here, don't proceed with shift closing
        }

        // No hold orders, proceed to get shift summary
        loadShiftSummary();
      })
      .catch(err => {
        console.error('Error checking hold orders:', err);
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Failed to check hold orders',
          confirmButtonColor: '#d33'
        });
      });
  });

  function loadShiftSummary() {
    fetch('ajax/get_shift_summary.php')
      .then(res => res.json())
      .then(data => {
        if (data.status === 'success') {
          currentShiftData = data;
          displayShiftSummary(data);
          
          // Show the summary modal
          const summaryModal = new bootstrap.Modal(document.getElementById('shiftSummaryModal'));
          summaryModal.show();
          
          // Hide the close shift modal
          const closeModal = bootstrap.Modal.getInstance(document.getElementById('closeShiftModal'));
          if (closeModal) {
            closeModal.hide();
          }
        } else {
          Swal.fire({
            icon: 'error',
            title: 'Error',
            text: data.message || 'Failed to load shift summary',
            confirmButtonColor: '#d33'
          });
        }
      })
      .catch(err => {
        console.error('Error loading shift summary:', err);
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Failed to load shift summary',
          confirmButtonColor: '#d33'
        });
      });
  }

     function displayShiftSummary(data) {
     const content = document.getElementById('shiftSummaryContent');
     
     // Validate required data
     if (!data.shift_data || !data.user_info) {
       content.innerHTML = '<div class="alert alert-danger">Error: Missing shift data</div>';
       return;
     }
     
     let html = `
      <div class="row">
        <div class="col-md-6">
          <h6 class="text-primary">Shift Details</h6>
          <table class="table table-sm">
            <tr><td><strong>Shift ID:</strong></td><td>${data.shift_data.shift_id}</td></tr>
                                      <tr><td><strong>Cashier:</strong></td><td>${data.user_info.username}</td></tr>
             <tr><td><strong>Store:</strong></td><td>${data.store_info ? data.store_info.store_name : 'Unknown Store'}</td></tr>
            <tr><td><strong>Start Time:</strong></td><td>${new Date(data.shift_data.start_time).toLocaleString()}</td></tr>
          </table>
        </div>
        <div class="col-md-6">
          <h6 class="text-primary">Cash Summary</h6>
          <table class="table table-sm">
            <tr><td><strong>Opening Cash:</strong></td><td class="text-end">${formatCurrency(data.shift_data.opening_cash)}</td></tr>
            <tr><td><strong>Cash Sales:</strong></td><td class="text-end">${formatCurrency(data.shift_data.cash_sales)}</td></tr>
            <tr><td><strong>Cash In:</strong></td><td class="text-end">${formatCurrency(data.shift_data.cash_in)}</td></tr>
            <tr><td><strong>Cash Out:</strong></td><td class="text-end">-${formatCurrency(data.shift_data.cash_out)}</td></tr>
            <tr class="table-warning"><td><strong>Expected Cash:</strong></td><td class="text-end"><strong>${formatCurrency(data.shift_data.expected_cash)}</strong></td></tr>
            <tr class="table-info"><td><strong>Actual Cash:</strong></td><td class="text-end"><strong>${formatCurrency(currentClosingCash)}</strong></td></tr>
                         <tr class="${(currentClosingCash - data.shift_data.expected_cash) >= 0 ? 'table-success' : 'table-danger'}">
               <td><strong>Discrepancy:</strong></td>
               <td class="text-end"><strong>${(currentClosingCash - data.shift_data.expected_cash) >= 0 ? '+' : ''}${formatCurrency(currentClosingCash - data.shift_data.expected_cash)}</strong></td>
             </tr>
          </table>
        </div>
      </div>
      
      <div class="row mt-3">
        <div class="col-12">
          <h6 class="text-primary">Sales Summary</h6>
          <table class="table table-sm table-bordered">
            <thead class="table-light">
              <tr>
                <th>Payment Method</th>
                <th class="text-center">Transactions</th>
                <th class="text-end">Total Amount</th>
                <th class="text-end">Tax</th>
                <th class="text-end">Discount</th>
                <th class="text-end">Net Amount</th>
              </tr>
            </thead>
            <tbody>`;

    data.sales_summary.forEach(sale => {
      html += `
        <tr>
          <td><strong>${sale.payment_method.toUpperCase()}</strong></td>
          <td class="text-center">${sale.transaction_count}</td>
          <td class="text-end">${formatCurrency(sale.total_amount)}</td>
          <td class="text-end">${formatCurrency(sale.total_tax)}</td>
          <td class="text-end">${formatCurrency(sale.total_discount)}</td>
          <td class="text-end"><strong>${formatCurrency(sale.net_amount)}</strong></td>
        </tr>`;
    });

    html += `
            </tbody>
            <tfoot class="table-warning">
              <tr>
                <td><strong>TOTAL</strong></td>
                <td class="text-center"><strong>${data.totals.transaction_count}</strong></td>
                <td class="text-end"><strong>${formatCurrency(data.totals.total_sales)}</strong></td>
                <td class="text-end"><strong>${formatCurrency(data.totals.total_tax)}</strong></td>
                <td class="text-end"><strong>${formatCurrency(data.totals.total_discount)}</strong></td>
                <td class="text-end"><strong>${formatCurrency(data.totals.total_net)}</strong></td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>`;

    content.innerHTML = html;
  }

     function formatCurrency(amount) {
     return new Intl.NumberFormat('en-US', {
       minimumFractionDigits: 2,
       maximumFractionDigits: 2
     }).format(amount);
   }

  // Print shift summary
  document.getElementById('printShiftSummary').addEventListener('click', function() {
    if (currentShiftData) {
      const printUrl = `print_shift_summary.php?shift_id=${currentShiftData.shift_data.shift_id}&closing_cash=${currentClosingCash}`;
      window.open(printUrl, '_blank');
    }
  });

  // Confirm shift close
  document.getElementById('confirmShiftClose').addEventListener('click', function() {
    if (!currentShiftData) return;

    // Submit the actual shift close
    const formData = new FormData();
    formData.append('closing_cash', currentClosingCash);

    fetch('close_shift.php', {
      method: 'POST',
      body: formData
    })
    .then(res => res.json())
    .then(data => {
      if (data.status === 'success') {
        Swal.fire({
          icon: 'success',
          title: 'Shift Closed Successfully',
          text: 'The shift has been closed and you will be redirected to login.',
          confirmButtonColor: '#3085d6',
          confirmButtonText: 'OK'
        }).then(() => {
          window.location.href = 'logout.php';
        });
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: data.message || 'Failed to close shift',
          confirmButtonColor: '#d33'
        });
      }
    })
    .catch(err => {
      console.error('Error closing shift:', err);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Network error occurred while closing shift',
        confirmButtonColor: '#d33'
      });
    });
  });
</script>
