<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\PosService; use App\Core\Database;
PosService::requireAccess();
$vendorId = PosService::currentVendorId();
$register = PosService::defaultRegister($vendorId);
$user = current_user();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) { set_flash('error','Invalid security token.'); redirect('pos/shifts.php'); }
    $action = $_POST['action'] ?? '';
    if ($action === 'open') {
        $res = PosService::openShift((int)($register['id'] ?? 0), (int)$user['id'], (float)($_POST['opening_cash'] ?? 0));
        set_flash($res['ok'] ? 'success' : 'error', $res['message']);
    } elseif ($action === 'close') {
        $shiftId = (int)($_POST['shift_id'] ?? 0);
        $res = PosService::closeShift($shiftId, (int)$user['id'], (float)($_POST['closing_cash'] ?? 0));
        set_flash($res['ok'] ? 'success' : 'error', $res['message']);
    } elseif ($action === 'cash_movement') {
        $shiftId = (int)($_POST['shift_id'] ?? 0);
        $res = PosService::cashMovement($shiftId, (int)$user['id'], (string)($_POST['movement_type'] ?? ''), (float)($_POST['amount'] ?? 0), (string)($_POST['reason'] ?? ''));
        set_flash($res['ok'] ? 'success' : 'error', $res['message']);
    }
    redirect('pos/shifts.php');
}
$shift = $register ? PosService::currentShift((int)$register['id'], (int)$user['id']) : null;
$recent = App\Core\Database::fetchAll('SELECT ps.*,pr.name AS register_name,u.name AS cashier_name FROM pos_shifts ps LEFT JOIN pos_registers pr ON pr.id=ps.register_id LEFT JOIN users u ON u.id=ps.cashier_id WHERE pr.vendor_id=? ORDER BY ps.id DESC LIMIT 20', [$vendorId]);
$pageTitle = 'Open / Close Shift | Pro POS';
require_once __DIR__ . '/partials/header.php';
?>
<div class="row g-3">
  <div class="col-lg-5">
    <div class="card pos-card"><div class="card-header bg-white"><strong><?= $shift ? 'Close Current Shift' : 'Open Shift' ?></strong></div><div class="card-body">
      <?php if(!$register): ?><div class="alert alert-warning">No register found. Create one from POS Settings.</div><?php elseif(!$shift): ?>
      <form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="open"><label class="form-label">Opening cash amount</label><input class="form-control form-control-lg" name="opening_cash" type="number" step="0.01" value="0"><button class="btn btn-primary mt-3">Open Shift</button></form>
      <?php else: ?>
      <div class="pos-total-box mb-3"><div><span>Opened</span><strong><?= e($shift['opened_at'] ?? '') ?></strong></div><div><span>Opening Cash</span><strong><?= money($shift['opening_cash'] ?? 0) ?></strong></div><div><span>Expected Cash</span><strong><?= money($shift['expected_cash'] ?? 0) ?></strong></div></div>
      <form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="close"><input type="hidden" name="shift_id" value="<?= (int)$shift['id'] ?>"><label class="form-label">Closing counted cash</label><input class="form-control form-control-lg" name="closing_cash" type="number" step="0.01" value="<?= e($shift['expected_cash'] ?? 0) ?>"><button class="btn btn-danger mt-3">Close Shift</button></form>
      <?php endif; ?>
    </div></div>
  </div>
  <div class="col-lg-7">
    <div class="card pos-card"><div class="card-header bg-white"><strong>Cash In / Cash Out</strong></div><div class="card-body">
      <?php if($shift): ?><form method="post" class="row g-2"><?= csrf_field() ?><input type="hidden" name="action" value="cash_movement"><input type="hidden" name="shift_id" value="<?= (int)$shift['id'] ?>"><div class="col-md-3"><select class="form-select" name="movement_type"><option value="cash_in">Cash In</option><option value="cash_out">Cash Out</option></select></div><div class="col-md-3"><input class="form-control" name="amount" type="number" step="0.01" placeholder="Amount"></div><div class="col-md-4"><input class="form-control" name="reason" placeholder="Reason"></div><div class="col-md-2 d-grid"><button class="btn btn-primary">Save</button></div></form><?php else: ?><p class="text-muted mb-0">Open a shift to record cash drawer movements.</p><?php endif; ?>
    </div></div>
    <div class="card pos-card mt-3"><div class="card-header bg-white"><strong>Recent Shifts</strong></div><div class="table-responsive"><table class="table mb-0"><thead><tr><th>Register</th><th>Cashier</th><th>Open</th><th>Close</th><th>Status</th></tr></thead><tbody><?php if(!$recent): ?><?= table_empty(5,'No shifts yet.') ?><?php else: foreach($recent as $row): ?><tr><td><?= e($row['register_name'] ?? '') ?></td><td><?= e($row['cashier_name'] ?? '') ?></td><td><?= money($row['opening_cash'] ?? 0) ?></td><td><?= money($row['closing_cash'] ?? 0) ?></td><td><?= badge($row['status'] ?? 'open') ?></td></tr><?php endforeach; endif; ?></tbody></table></div></div>
  </div>
</div>
<?php require_once __DIR__ . '/partials/footer.php'; ?>
