<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$username = $_SESSION['username'] ?? 'Guest';
$current_user = $_SESSION['username'] ?? '';

$date_from = $_GET['date_from'] ?? date('Y-m-d');
$date_to   = $_GET['date_to'] ?? date('Y-m-d');

/* ================= CHECK SHIFT STATUS ================= */
$shift_check = $conn->query("
    SELECT * FROM shifts 
    WHERE DATE(date_from) = '$date_from'
      AND status = 'CLOSED'
    LIMIT 1
")->fetch_assoc();

$shift_closed = $shift_check ? true : false;

/* ================= PAYMENTS ================= */
$payments = $conn->query("
    SELECT 
        p.id,
        p.payment_date,
        p.amount,
        p.method,
        p.created_by,
        g.name AS paid_by,
        i.invoice_number
    FROM payments p
    LEFT JOIN guests g ON g.id = p.guest_id
    LEFT JOIN invoices i ON i.guest_id = p.guest_id
    WHERE DATE(p.payment_date) BETWEEN '$date_from' AND '$date_to'
      AND p.state = 4
    ORDER BY p.payment_date ASC
");

$rows = [];

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

while($r = $payments->fetch_assoc()){
    $rows[] = $r;

    $total_all += $r['amount'];

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

/* ================= SHIFT INFO ================= */
$shift = $conn->query("
    SELECT * FROM shifts 
    WHERE DATE(date_from) = '$date_from'
    ORDER BY id DESC
    LIMIT 1
")->fetch_assoc();

$shift_no   = $shift['shift_no'] ?? 'NOT CLOSED';
$time_ended = $shift['closed_at'] ?? date('h:i:s A');
$cashier_name = $rows[0]['created_by'] ?? $current_user;
?>

<style>
body{
    background:#f4f6f9;
    font-family:Arial;
}

#printArea{
    background:#fff;
    padding:20px;
    border-radius:10px;
}

table{
    font-size:13px;
}

th{
    background:#222;
    color:#fff;
}
</style>

<div class="container mt-4">

<!-- ================= FILTER ================= -->
<form method="GET" class="row mb-3">
    <div class="col-md-5">
        <input type="date" name="date_from" value="<?= $date_from ?>" class="form-control">
    </div>
    <div class="col-md-5">
        <input type="date" name="date_to" value="<?= $date_to ?>" class="form-control">
    </div>
    <div class="col-md-2">
        <button class="btn btn-success w-100">Filter</button>
    </div>
</form>

<!-- ================= CLOSE SHIFT BUTTON ================= -->
<?php if(!$shift_closed): ?>
<form method="POST" action="shift_close.php">
    <button class="btn btn-danger mb-3">
        <i class="fa fa-lock"></i> Close Shift
    </button>
</form>
<?php else: ?>
<div class="alert alert-warning mb-3">
    Shift already closed.
</div>
<?php endif; ?>

<div id="printArea">

<!-- ================= HEADER ================= -->
<div class="text-center">
    <h2>RAMS EXECUTIVE LODGE</h2>
    <h4>Cashier Report</h4>
</div>

<!-- ================= SHIFT INFO ================= -->
<table class="table table-borderless">
<tr>
    <td><b>Shift Date:</b> <?= date('d/m/Y', strtotime($date_from)) ?> - <?= date('d/m/Y', strtotime($date_to)) ?></td>
    <td><b>Time Ended:</b> <?= $time_ended ?></td>
</tr>
<tr>
    <td><b>Shift No:</b> <?= $shift_no ?></td>
    <td><b>Cashier:</b> <?= strtoupper($cashier_name) ?></td>
</tr>
</table>

<!-- ================= PAYMENTS TABLE ================= -->
<table class="table table-bordered">
<thead>
<tr>
    <th>Time</th>
    <th>Date</th>
    <th>Paid By</th>
    <th>Invoice No</th>
    <th>Amount</th>
    <th>Method</th>
    <th>Cashier</th>
</tr>
</thead>
<tbody>
<?php foreach($rows as $r): ?>
<tr>
    <td><?= date('h:i:s A', strtotime($r['payment_date'])) ?></td>
    <td><?= date('d/m/Y', strtotime($r['payment_date'])) ?></td>
    <td><?= $r['paid_by'] ?></td>
    <td><?= $r['invoice_number'] ?? '-' ?></td>
    <td><?= number_format($r['amount'],2) ?></td>
    <td><?= strtoupper($r['method']) ?></td>
    <td><?= strtoupper($r['created_by']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<!-- ================= SUMMARY ================= -->
<table class="table table-bordered">
<tr>
    <td><b>CASH</b></td>
    <td><?= number_format($total_cash,2) ?></td>
</tr>
<tr>
    <td><b>BANK</b></td>
    <td><?= number_format($total_bank,2) ?></td>
</tr>
<tr>
    <td><b>TOTAL</b></td>
    <td><b><?= number_format($total_all,2) ?></b></td>
</tr>
</table>

</div>

<!-- ================= PRINT BUTTON ================= -->
<a href="shifts.php" class="btn btn-secondary mt-3">
    <i class="fa fa-arrow-left"></i> Back
</a>

<script>
function printReport(){
    var content = document.getElementById("printArea").innerHTML;
    var w = window.open("", "", "width=1200,height=800");

    w.document.write(`
        <html>
        <head>
        <title>Cashier Report</title>
        <style>
            body{font-family:Arial;padding:20px;font-size:12px;}
            table{width:100%;border-collapse:collapse;}
            table,th,td{border:1px solid #000;}
            th,td{padding:6px;text-align:center;}
            h2,h4{text-align:center;}
        </style>
        </head>
        <body>${content}</body>
        </html>
    `);

    w.document.close();
    w.print();
}
</script>

<?php include 'includes/footer.php'; ?>