<?php
include 'db.php';
session_start();

$cashier = $_SESSION['username'] ?? 'UNKNOWN';

$date_from = date('Y-m-d');
$date_to   = date('Y-m-d');

/* ================= CHECK IF SHIFT ALREADY CLOSED ================= */
$check = $conn->query("
    SELECT id 
    FROM shifts 
    WHERE date_from = '$date_from'
      AND status = 'CLOSED'
    LIMIT 1
");

if($check->num_rows > 0){
    header("Location: cashier_report.php?error=shift_already_closed");
    exit;
}

/* ================= GET TOTALS ================= */
$payments = $conn->query("
    SELECT amount, method
    FROM payments
    WHERE DATE(payment_date) BETWEEN '$date_from' AND '$date_to'
      AND state = 4
");

$total_cash = 0;
$total_bank = 0;
$total_all  = 0;

while($r = $payments->fetch_assoc()){
    $total_all += $r['amount'];

    if(strtolower($r['method']) == 'cash'){
        $total_cash += $r['amount'];
    } else {
        $total_bank += $r['amount'];
    }
}

$over_short = 0;

/* ================= GENERATE SHIFT NO ================= */
$shift_no = "SHIFT-" . date("YmdHis");

/* ================= INSERT SHIFT ================= */
$conn->query("
    INSERT INTO shifts 
    (shift_no, cashier, date_from, date_to, total_cash, total_bank, total_all, over_short, status, closed_at)
    VALUES 
    ('$shift_no', '$cashier', '$date_from', '$date_to', $total_cash, $total_bank, $total_all, $over_short, 'CLOSED', NOW())
");

header("Location: cashier_report.php?closed=1");
exit;
?>