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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$today = date('Y-m-d');

// ================= FILTERS =================
$status_filter = $_GET['status'] ?? '';
$guest_filter = $_GET['guest'] ?? '';
$room_filter = $_GET['room'] ?? '';
$from_date = $_GET['from'] ?? '';
$to_date = $_GET['to'] ?? '';
$method_filter = $_GET['method'] ?? '';
$sort_by = $_GET['sort_by'] ?? 'p.id';
$sort_order = $_GET['sort_order'] ?? 'DESC';

// Allowed sorting columns
$allowed_sort = ['p.id','p.amount','p.status','p.payment_date','p.method'];
if(!in_array($sort_by,$allowed_sort)) $sort_by = 'p.id';
$sort_order = strtoupper($sort_order)=='ASC'?'ASC':'DESC';

// ================= GET DROPDOWN OPTIONS =================
$status_options = ['Paid','Pending','Failed'];

// Guests dropdown
$guests_res = $conn->query("SELECT id, name FROM guests ORDER BY name ASC");
$guest_options = [];
while($g = $guests_res->fetch_assoc()) $guest_options[$g['id']] = $g['name'];

// Rooms dropdown
$rooms_res = $conn->query("SELECT id, room_number FROM rooms ORDER BY room_number ASC");
$room_options = [];
while($r = $rooms_res->fetch_assoc()) $room_options[$r['id']] = $r['room_number'];

// Payment methods dropdown
$methods_res = $conn->query("SELECT DISTINCT method FROM payments ORDER BY method ASC");
$method_options = [];
while($m = $methods_res->fetch_assoc()) $method_options[] = $m['method'];

// ================= BUILD WHERE CLAUSE =================
$where = [];
if($status_filter) $where[] = "p.status='".$conn->real_escape_string($status_filter)."'";
if($guest_filter) $where[] = "g.id=".$conn->real_escape_string($guest_filter);
if($room_filter) $where[] = "rm.id=".$conn->real_escape_string($room_filter);
if($method_filter) $where[] = "p.method='".$conn->real_escape_string($method_filter)."'";
if($from_date) $where[] = "p.payment_date >= '".$conn->real_escape_string($from_date)."'";
if($to_date) $where[] = "p.payment_date <= '".$conn->real_escape_string($to_date)."'";

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

// ================= FETCH PAYMENTS =================
$query = "SELECT p.*, g.name AS guest_name, s.room_id, rm.room_number, rm.price AS room_price
          FROM payments p
          JOIN stays s ON p.guest_id = s.guest_id
          JOIN rooms rm ON s.room_id = rm.id
          JOIN guests g ON p.guest_id = g.id
          $where_sql
          ORDER BY $sort_by $sort_order";
$payments = $conn->query($query);

// ================= TOTAL SUMMARIES =================
$summary_query = "SELECT 
                    COUNT(*) AS total_payments,
                    SUM(CASE WHEN p.status='Paid' THEN p.amount ELSE 0 END) AS paid_total,
                    SUM(CASE WHEN p.status='Pending' THEN p.amount ELSE 0 END) AS pending_total,
                    SUM(CASE WHEN p.status='Failed' THEN p.amount ELSE 0 END) AS failed_total,
                    SUM(p.amount) AS total_amount
                  FROM payments p
                  JOIN stays s ON p.guest_id=s.guest_id
                  JOIN guests g ON p.guest_id=g.id
                  JOIN rooms rm ON s.room_id=rm.id
                  $where_sql";
$summary = $conn->query($summary_query)->fetch_assoc();

// ================= TODAY'S PAYMENTS =================
$today_query = "SELECT 
                  COUNT(*) AS today_count,
                  SUM(amount) AS today_total
                FROM payments
                WHERE DATE(payment_date)='$today'";
$today_summary = $conn->query($today_query)->fetch_assoc();
?>

<div class="container mt-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3><i class="fa fa-credit-card"></i> Payments</h3>
        <a href="invoices.php" class="btn btn-success"><i class="fa fa-file-invoice"></i>Make Payment</a>
    </div>

    <!-- ================= FILTER FORM ================= -->
    <form method="GET" class="row g-2 mb-3">
        <div class="col-md-2">
            <label>Status <i class="fa fa-info-circle text-muted" title="Filter by payment status"></i></label>
            <select name="status" class="form-control">
                <option value="">All</option>
                <?php foreach($status_options as $s): ?>
                    <option value="<?= $s ?>" <?= $status_filter==$s?'selected':'' ?>><?= $s ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-md-3">
            <label>Guest <i class="fa fa-user text-muted" title="Filter by guest"></i></label>
            <select name="guest" class="form-control">
                <option value="">All Guests</option>
                <?php foreach($guest_options as $id=>$name): ?>
                    <option value="<?= $id ?>" <?= $guest_filter==$id?'selected':'' ?>><?= htmlspecialchars($name) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-md-2">
            <label>Room # <i class="fa fa-bed text-muted" title="Filter by room"></i></label>
            <select name="room" class="form-control">
                <option value="">All Rooms</option>
                <?php foreach($room_options as $id=>$number): ?>
                    <option value="<?= $id ?>" <?= $room_filter==$id?'selected':'' ?>><?= htmlspecialchars($number) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-md-2">
            <label>Method <i class="fa fa-credit-card text-muted" title="Filter by payment method"></i></label>
            <select name="method" class="form-control">
                <option value="">All Methods</option>
                <?php foreach($method_options as $m): ?>
                    <option value="<?= htmlspecialchars($m) ?>" <?= $method_filter==$m?'selected':'' ?>><?= htmlspecialchars($m) ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-md-1">
            <label>From</label>
            <input type="date" name="from" class="form-control" value="<?= htmlspecialchars($from_date) ?>">
        </div>

        <div class="col-md-1">
            <label>To</label>
            <input type="date" name="to" class="form-control" value="<?= htmlspecialchars($to_date) ?>">
        </div>

        <div class="col-md-1 d-flex align-items-end">
            <button class="btn btn-primary form-control"><i class="fa fa-filter"></i> Filter</button>
        </div>
    </form>

    <!-- ================= TODAY'S PAYMENTS CARDS ================= -->
    <div class="row mb-3">
        <div class="col-md-3">
            <div class="card text-white bg-success mb-2">
                <div class="card-body">
                    <h5 class="card-title"><i class="fa fa-check-circle"></i> Today Paid</h5>
                    <p class="card-text"><?= number_format($today_summary['today_total'] ?? 0,2) ?> MWK</p>
                    <small><?= $today_summary['today_count'] ?? 0 ?> Payments</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-white bg-warning mb-2">
                <div class="card-body">
                    <h5 class="card-title"><i class="fa fa-hourglass-half"></i> Pending</h5>
                    <p class="card-text">Check pending payments</p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card text-white bg-danger mb-2">
                <div class="card-body">
                    <h5 class="card-title"><i class="fa fa-times-circle"></i> Failed</h5>
                    <p class="card-text">Check failed payments</p>
                </div>
            </div>
        </div>
    </div>

    <!-- ================= SUMMARY ================= -->
    <div class="mb-3">
        <strong><i class="fa fa-list-alt"></i> Summary:</strong>
        Total Payments: <?= $summary['total_payments'] ?> | 
        Paid: <?= number_format($summary['paid_total'],2) ?> | 
        Pending: <?= number_format($summary['pending_total'],2) ?> | 
        Failed: <?= number_format($summary['failed_total'],2) ?> | 
        Total Amount: <?= number_format($summary['total_amount'],2) ?>
    </div>

    <!-- ================= PAYMENTS TABLE ================= -->
    <table class="table table-bordered table-striped table-hover">
        <thead class="table-dark">
            <tr>
                <th>ID <i class="fa fa-sort"></i></th>
                <th>Guest</th>
                <th>Room #</th>
                <th>Amount <i class="fa fa-sort"></i></th>
                <th>Method</th>
                <th>Status</th>
                <th>Payment Date <i class="fa fa-sort"></i></th>
            </tr>
        </thead>
        <tbody>
            <?php if($payments->num_rows==0): ?>
            <tr>
                <td colspan="8" class="text-center"><i class="fa fa-exclamation-triangle"></i> No payments found</td>
            </tr>
            <?php else: ?>
            <?php while($p = $payments->fetch_assoc()): ?>
            <tr class="<?= $p['status']=='Paid' ? 'table-success' : ($p['status']=='Pending' ? 'table-warning' : 'table-danger') ?>">
                <td><?= $p['id'] ?></td>
                <td><?= htmlspecialchars($p['guest_name']) ?></td>
                <td><?= htmlspecialchars($p['room_number']) ?></td>
                <td><?= number_format($p['amount'],2) ?></td>
                <td><?= htmlspecialchars($p['method']) ?></td>
                <td><i class="<?= $p['status']=='Paid'?'fa fa-check-circle text-success':($p['status']=='Pending'?'fa fa-hourglass-half text-warning':'fa fa-times-circle text-danger') ?>"></i> <?= $p['status'] ?></td>
                <td><?= $p['payment_date'] ?></td>
            </tr>
            <?php endwhile; ?>
            <?php endif; ?>
        </tbody>
    </table>
</div>

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