<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$CI =& get_instance();
$session = $session;
$currency = $CI->currency('');
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title><?= $page_title; ?> | <?= $this->session->userdata('store_name'); ?></title>
  <link rel="stylesheet" href="<?= $theme_link; ?>bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="<?= $theme_link; ?>css/font-awesome-4.7.0/css/font-awesome.min.css">
  <style>
    * { box-sizing: border-box; }
    html { font-size: 16px; }
    @media (min-width: 768px) { html { font-size: 16px; } }
    body { background: #f4f6f9; padding: 24px 16px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
    @media (min-width: 768px) { body { padding: 40px 24px; padding-top: 60px; } }
    .cash-page { max-width: 480px; margin: 0 auto; }
    @media (min-width: 768px) { .cash-page { max-width: 520px; } }
    @media (min-width: 992px) { .cash-page { max-width: 560px; } }
    .cash-card { background: #fff; border-radius: 10px; box-shadow: 0 2px 12px rgba(0,0,0,0.08); border: 1px solid #e8eaed; overflow: hidden; margin-bottom: 20px; }
    @media (min-width: 768px) { .cash-card { box-shadow: 0 4px 20px rgba(0,0,0,0.1); border-radius: 12px; margin-bottom: 24px; } }
    .cash-card-header { padding: 20px 24px; border-bottom: 1px solid #eee; text-align: center; }
    @media (min-width: 768px) { .cash-card-header { padding: 28px 32px 24px; } }
    .cash-card-header h1 { margin: 0; font-size: 1.5rem; font-weight: 600; color: #1a1a1a; }
    @media (min-width: 768px) { .cash-card-header h1 { font-size: 1.75rem; } }
    .cash-card-header h1 i { margin-right: 8px; color: #3c8dbc; }
    .cash-card-body { padding: 24px; }
    @media (min-width: 768px) { .cash-card-body { padding: 28px 32px; } }
    .session-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #f0f0f0; font-size: 1rem; }
    .session-row:last-child { border-bottom: 0; }
    .session-row .label { color: #555; }
    .session-row .value { font-weight: 600; color: #222; }
    .btn-block-m { display: block; width: 100%; margin-bottom: 10px; min-height: 48px; font-size: 1.05rem; border-radius: 8px; }
    .btn-block-m:last-child { margin-bottom: 0; }
    @media (min-width: 768px) { .btn-block-m { min-height: 44px; padding: 10px 20px; font-size: 1rem; } }
    .modal-body .form-group label { font-weight: 600; }
    .summary-box { background: #f8f9fa; border-radius: 8px; padding: 14px 16px; margin-bottom: 16px; }
    @media (min-width: 768px) { .summary-box { padding: 18px 20px; } }
    .variance { font-size: 1.1rem; font-weight: 700; }
    .variance.over { color: #28a745; }
    .variance.short { color: #dc3545; }
    .variance.zero { color: #666; }
  </style>
</head>
<body>
  <div class="cash-page">
    <div class="cash-card">
      <div class="cash-card-header">
        <h1><i class="fa fa-money"></i> Cash Register – Session Open</h1>
        <p class="text-muted" style="margin: 8px 0 0; font-size: 1rem;">Manage opening, closing, and go to POS from here.</p>
      </div>
      <div class="cash-card-body">
        <div class="session-row"><span class="label">Opened at</span><span class="value"><?= date_format(date_create($session->opened_at), 'd M Y, H:i'); ?></span></div>
        <div class="session-row"><span class="label">Opening amount (posted)</span><span class="value"><?= $currency . number_format($opening_amount, 2); ?></span></div>
        <?php if (isset($drawer_base) && $drawer_base != $opening_amount): ?>
        <div class="session-row"><span class="label">Total in drawer at start</span><span class="value"><?= $currency . number_format($drawer_base, 2); ?></span></div>
        <?php endif; ?>
        <?php if (!empty($account_name)): ?>
        <div class="session-row"><span class="label">Credit to account</span><span class="value"><?= htmlspecialchars($account_name); ?></span></div>
        <?php endif; ?>
        <?php if (!empty($session->opening_note)): ?>
        <div class="session-row"><span class="label">Note</span><span class="value"><?= htmlspecialchars($session->opening_note); ?></span></div>
        <?php endif; ?>
      </div>
    </div>
    <div class="cash-card">
      <div class="cash-card-body">
        <a href="<?= $base_url; ?>pos" class="btn btn-success btn-block-m"><i class="fa fa-calculator"></i> Go to POS</a>
        <button type="button" class="btn btn-primary btn-block-m" id="btn-edit-opening"><i class="fa fa-edit"></i> Edit Opening</button>
        <button type="button" class="btn btn-warning btn-block-m" id="btn-close-register"><i class="fa fa-lock"></i> Close Register</button>
        <a href="<?= $base_url; ?>dashboard" class="btn btn-default btn-block-m">Back to Dashboard</a>
      </div>
    </div>
  </div>

  <!-- Edit Opening Modal -->
  <div class="modal fade" id="edit-opening-modal" tabindex="-1">
    <div class="modal-dialog" style="max-width:420px; margin: 1rem auto;">
      <div class="modal-content">
        <div class="modal-header" style="background: #3c8dbc; color: #fff;"><button type="button" class="close" data-dismiss="modal" style="color:#fff; opacity:0.9;"><span>&times;</span></button><h4 class="modal-title"><i class="fa fa-edit"></i> Edit Opening</h4></div>
        <div class="modal-body">
          <p class="text-muted small">Correct the opening amount or the account it was credited to.</p>
          <input type="hidden" id="edit-session-id" value="<?= (int)$session->id; ?>">
          <div class="form-group">
            <label>Opening amount (posted) <span class="text-danger">*</span></label>
            <input type="text" class="form-control" id="edit_opening_amount" value="<?= $opening_amount; ?>" placeholder="0.00" inputmode="decimal">
          </div>
          <div class="form-group">
            <label>Total in drawer at start (optional)</label>
            <input type="text" class="form-control" id="edit_drawer_total" value="<?= isset($session->drawer_total_at_open) && $session->drawer_total_at_open !== null && $session->drawer_total_at_open !== '' ? $session->drawer_total_at_open : ''; ?>" placeholder="Same as opening if no carry-over" inputmode="decimal">
          </div>
          <div class="form-group">
            <label>Credit to account</label>
            <select class="form-control" id="edit_account_id"><option value="">-- Select cash account --</option><?= get_accounts_select_list(isset($session->account_id) ? $session->account_id : ''); ?></select>
          </div>
          <div class="form-group">
            <label>Note (optional)</label>
            <textarea class="form-control" id="edit_opening_note" rows="2"><?= htmlspecialchars($session->opening_note ?: ''); ?></textarea>
          </div>
          <div id="edit-opening-msg" class="alert" style="display:none;"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-primary" id="edit-opening-submit"><i class="fa fa-check"></i> Update Opening</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Close Register Modal -->
  <div class="modal fade" id="close-register-modal" tabindex="-1">
    <div class="modal-dialog" style="max-width:440px; margin: 1rem auto;">
      <div class="modal-content">
        <div class="modal-header" style="background: #f0ad4e; color: #fff;"><button type="button" class="close" data-dismiss="modal" style="color:#fff; opacity:0.9;"><span>&times;</span></button><h4 class="modal-title"><i class="fa fa-lock"></i> Close Register</h4></div>
        <div class="modal-body">
          <div class="summary-box">
            <div class="session-row"><span class="label">Drawer at start</span><span class="value"><?= $currency . number_format(isset($drawer_base) ? $drawer_base : $opening_amount, 2); ?></span></div>
            <div class="session-row"><span class="label">Cash from sales</span><span class="value"><?= $currency . number_format($cash_from_sales, 2); ?></span></div>
            <div class="session-row"><span class="label">Expected in drawer</span><span class="value"><?= $currency . number_format($expected_closing, 2); ?></span></div>
          </div>
          <p class="text-muted small">Enter the actual cash count. Variance shows over/short.</p>
          <div class="form-group">
            <label>Actual closing amount <span class="text-danger">*</span></label>
            <input type="text" class="form-control" id="closing_amount" value="<?= number_format($expected_closing, 2, '.', ''); ?>" placeholder="0.00" inputmode="decimal" style="font-size:1.2rem;">
          </div>
          <div class="form-group" id="variance-row" style="font-size:1.1rem;">
            <strong>Variance:</strong> <span id="variance-display" class="variance zero"><?= $currency; ?>0.00</span>
          </div>
          <div class="form-group">
            <label>Note (optional)</label>
            <textarea class="form-control" id="closing_note" rows="2" placeholder="e.g. End of shift"></textarea>
          </div>
          <div id="close-register-msg" class="alert" style="display:none;"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-warning" id="close-register-submit"><i class="fa fa-lock"></i> Close Register</button>
        </div>
      </div>
    </div>
  </div>

  <script src="<?= $theme_link; ?>plugins/jQuery/jquery-2.2.3.min.js"></script>
  <script src="<?= $theme_link; ?>bootstrap/js/bootstrap.min.js"></script>
  <script>
    var base_url = <?= json_encode(base_url()); ?>;
    var expectedClosing = <?= json_encode($expected_closing); ?>;
    var currencySymbol = <?= json_encode($currency); ?>;
    var csrfName = <?= json_encode($CI->security->get_csrf_token_name()); ?>;
    var csrfHash = <?= json_encode($CI->security->get_csrf_hash()); ?>;

    $('#btn-edit-opening').on('click', function(){ $('#edit-opening-msg').hide(); $('#edit-opening-modal').modal('show'); });
    $('#edit-opening-submit').on('click', function(){
      var amt = parseFloat($('#edit_opening_amount').val().replace(/,/g, '')) || 0;
      var accountId = $('#edit_account_id').val();
      var note = $('#edit_opening_note').val();
      var $msg = $('#edit-opening-msg');
      if (amt > 0 && !accountId) { $msg.removeClass('alert-success').addClass('alert-danger').html('Select cash account when amount &gt; 0.').show(); return; }
      $msg.hide();
      $('#edit-opening-submit').prop('disabled', true);
      var drawerTotal = $('#edit_drawer_total').val().replace(/,/g, '');
      var data = { session_id: $('#edit-session-id').val(), opening_amount: amt, account_id: accountId || '', opening_note: note, drawer_total_at_open: drawerTotal || '' };
      data[csrfName] = csrfHash;
      $.post(base_url + 'cash_register/update_opening', data, function(res){
        if (res.success) { $('#edit-opening-modal').modal('hide'); window.location.reload(); }
        else { $msg.removeClass('alert-success').addClass('alert-danger').html(res.message || 'Update failed.').show(); }
        $('#edit-opening-submit').prop('disabled', false);
      }, 'json').fail(function(){ $msg.removeClass('alert-success').addClass('alert-danger').html('Request failed.').show(); $('#edit-opening-submit').prop('disabled', false); });
    });

    $('#btn-close-register').on('click', function(){
      $('#closing_amount').val(expectedClosing.toFixed(2));
      $('#close-register-msg').hide();
      updateVariance();
      $('#close-register-modal').modal('show');
    });
    $('#closing_amount').on('input', function(){ updateVariance(); });
    function updateVariance(){
      var actual = parseFloat($('#closing_amount').val().replace(/,/g, '')) || 0;
      var v = actual - expectedClosing;
      var $v = $('#variance-display').removeClass('over short zero');
      $v.text(currencySymbol + v.toFixed(2));
      if (v > 0) $v.addClass('over'); else if (v < 0) $v.addClass('short'); else $v.addClass('zero');
    }
    $('#close-register-submit').on('click', function(){
      var amt = $('#closing_amount').val().replace(/,/g, '');
      var note = $('#closing_note').val();
      var $msg = $('#close-register-msg');
      $msg.hide();
      $('#close-register-submit').prop('disabled', true);
      var data = { closing_amount: amt, closing_note: note };
      data[csrfName] = csrfHash;
      $.post(base_url + 'cash_register/close_session', data, function(res){
        if (res.success) { $('#close-register-modal').modal('hide'); window.location.href = base_url + 'cash_register'; }
        else { $msg.removeClass('alert-success').addClass('alert-danger').html(res.message || 'Failed.').show(); }
        $('#close-register-submit').prop('disabled', false);
      }, 'json').fail(function(){ $msg.removeClass('alert-success').addClass('alert-danger').html('Request failed.').show(); $('#close-register-submit').prop('disabled', false); });
    });
  </script>
</body>
</html>
