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

// ================= HANDLE NEW PAYMENT =================
if(isset($_POST['add_payment'])){
    $guest_id = $_POST['guest_id'] ?: null;
    $amount   = floatval($_POST['amount']);
    $type     = $_POST['type'];
    $user_id  = $_SESSION['user_id']; // current cashier
    $date     = $_POST['payment_date'] ?: date('Y-m-d H:i:s');

    $stmt = $conn->prepare("INSERT INTO payments (guest_id, amount, type, user_id, payment_date) VALUES (?,?,?,?,?)");
    $stmt->bind_param("idiss", $guest_id, $amount, $type, $user_id, $date);
    $stmt->execute();
    echo "<script>alert('Payment added successfully');window.location='cashier_transactions.php';</script>";
}

// ================= FETCH FILTER VALUES =================
$filter_guest   = $_GET['guest_id'] ?? '';
$filter_cashier = $_GET['cashier_id'] ?? '';
$filter_type    = $_GET['type'] ?? '';
$filter_from    = $_GET['from'] ?? '';
$filter_to      = $_GET['to'] ?? '';

// ================= BUILD WHERE CLAUSE =================
$where = [];
if($filter_guest)   $where[] = "p.guest_id=".intval($filter_guest);
if($filter_cashier) $where[] = "p.user_id=".intval($filter_cashier);
if($filter_type)    $where[] = "p.type='".$conn->real_escape_string($filter_type)."'";
if($filter_from)    $where[] = "DATE(p.payment_date) >= '".$conn->real_escape_string($filter_from)."'";
if($filter_to)      $where[] = "DATE(p.payment_date) <= '".$conn->real_escape_string($filter_to)."'";

$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";

// ================= FETCH TRANSACTIONS =================
$transactions = $conn->query("
    SELECT p.id, p.payment_date, p.amount, p.type, 
           g.name AS guest_name, c.username AS cashier
    FROM payments p
    LEFT JOIN guests g ON p.guest_id=g.id
    LEFT JOIN users c ON p.user_id=c.id
    $where_sql
    ORDER BY p.payment_date DESC
");

// ================= FETCH GUESTS AND CASHIERS =================
$guests   = $conn->query("SELECT id, name FROM guests ORDER BY name");
$cashiers = $conn->query("SELECT id, username FROM users ORDER BY username");
?>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
<h4>Cashier Transactions Summary</h4>
<hr>

<!-- ======= FILTER FORM ======= -->
<form method="GET" class="row g-2 mb-4">
    <div class="col-md-2">
        <select name="guest_id" class="form-control">
            <option value="">All Guests</option>
            <?php while($g=$guests->fetch_assoc()): ?>
                <option value="<?= $g['id'] ?>" <?= $filter_guest==$g['id']?'selected':'' ?>><?= htmlspecialchars($g['name']) ?></option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="col-md-2">
        <select name="cashier_id" class="form-control">
            <option value="">All Cashiers</option>
            <?php while($c=$cashiers->fetch_assoc()): ?>
                <option value="<?= $c['id'] ?>" <?= $filter_cashier==$c['id']?'selected':'' ?>><?= htmlspecialchars($c['username']) ?></option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="col-md-2">
        <select name="type" class="form-control">
            <option value="">All Types</option>
            <option value="Room" <?= $filter_type=='Room'?'selected':'' ?>>Room</option>
            <option value="Bar" <?= $filter_type=='Bar'?'selected':'' ?>>Bar</option>
            <option value="Restaurant" <?= $filter_type=='Restaurant'?'selected':'' ?>>Restaurant</option>
            <option value="Room Service" <?= $filter_type=='Room Service'?'selected':'' ?>>Room Service</option>
            <option value="Laundry" <?= $filter_type=='Laundry'?'selected':'' ?>>Laundry</option>
              <option value="Conference" <?= $filter_type=='Conference'?'selected':'' ?>>Conference</option>
        </select>
    </div>
    <div class="col-md-2"><input type="date" name="from" class="form-control" value="<?= htmlspecialchars($filter_from) ?>" placeholder="From"></div>
    <div class="col-md-2"><input type="date" name="to" class="form-control" value="<?= htmlspecialchars($filter_to) ?>" placeholder="To"></div>
    <div class="col-md-2"><button class="btn btn-primary w-100">Filter</button></div>
</form>

<!-- ======= ADD PAYMENT FORM ======= -->
<button class="btn btn-success mb-3" type="button" data-bs-toggle="collapse" data-bs-target="#addPaymentForm">
    <i class="fa fa-plus"></i> Add Payment
</button>

<div class="collapse mb-4" id="addPaymentForm">
<form method="POST" class="row g-2">
    <div class="col-md-3">
        <select name="guest_id" class="form-control">
            <option value="">Walk-in / Guest</option>
            <?php $guests->data_seek(0); while($g=$guests->fetch_assoc()): ?>
                <option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['name']) ?></option>
            <?php endwhile; ?>
        </select>
    </div>
    <div class="col-md-2"><input type="number" step="0.01" name="amount" class="form-control" placeholder="Amount" required></div>
    <div class="col-md-3">
        <select name="type" class="form-control" required>
            <option value="Room">Room</option>
            <option value="Bar">Bar</option>
            <option value="Restaurant">Restaurant</option>
            <option value="Room Service">Room Service</option>
            <option value="Laundry">Laundry</option>
                <option value="Conference">Conference</option>
        </select>
    </div>
    <div class="col-md-2"><input type="datetime-local" name="payment_date" class="form-control"></div>
    <div class="col-md-2"><button name="add_payment" class="btn btn-success w-100">Add Payment</button></div>
</form>
</div>

<!-- ======= TRANSACTIONS TABLE ======= -->
<table class="table table-bordered table-striped table-sm">
<thead class="table-dark">
<tr>
    <th>#</th>
    <th>Date & Time</th>
    <th>Cashier</th>
    <th>Guest</th>
    <th>Payment Type</th>
    <th>Amount (MK)</th>
</tr>
</thead>
<tbody>
<?php 
$i = 1; 
$total_amount = 0;
while($t = $transactions->fetch_assoc()): 
    $total_amount += $t['amount'];
?>
<tr>
    <td><?= $i ?></td>
    <td><?= date('Y-m-d H:i', strtotime($t['payment_date'])) ?></td>
    <td><?= htmlspecialchars($t['cashier'] ?? 'N/A') ?></td>
    <td><?= htmlspecialchars($t['guest_name'] ?? 'Walk-in') ?></td>
    <td><?= htmlspecialchars($t['type']) ?></td>
    <td><?= number_format($t['amount'],2) ?></td>
</tr>
<?php $i++; endwhile; ?>
</tbody>
<tfoot class="table-dark">
<tr>
    <th colspan="5">Total Received</th>
    <th><?= number_format($total_amount,2) ?></th>
</tr>
</tfoot>
</table>
</div>

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