<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 4) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');
include('../../includes/footer.php');

$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$store_filter = isset($_GET['store_id']) ? intval($_GET['store_id']) : 0;
$cashier_filter = isset($_GET['cashier_id']) ? intval($_GET['cashier_id']) : 0;
$payment_method_filter = $_GET['payment_method'] ?? '';

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_from)) $date_from = date('Y-m-01');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date_to)) $date_to = date('Y-m-d');

$stores = $conn->query("SELECT id, store_name FROM stores WHERE deleted_at IS NULL ORDER BY store_name")->fetch_all(MYSQLI_ASSOC);
$cashiers = $conn->query("SELECT id, CONCAT(first_name, ' ', last_name) AS name FROM users WHERE role_id = 3")->fetch_all(MYSQLI_ASSOC);

$where = "WHERE DATE(st.created_at) BETWEEN ? AND ?";
$params = [$date_from, $date_to];
$types = "ss";

if ($store_filter > 0) {
    $where .= " AND st.store_id = ?";
    $params[] = $store_filter;
    $types .= "i";
}
if ($cashier_filter > 0) {
    $where .= " AND st.sold_by = ?";
    $params[] = $cashier_filter;
    $types .= "i";
}
if (!empty($payment_method_filter)) {
    $where .= " AND st.payment_method = ?";
    $params[] = $payment_method_filter;
    $types .= "s";
}

$stmt = $conn->prepare("
    SELECT st.*, s.store_name, u.first_name, u.last_name
    FROM sales_transactions st
    JOIN stores s ON st.store_id = s.id
    JOIN users u ON st.sold_by = u.id
    $where
    ORDER BY st.created_at DESC
");
$stmt->bind_param($types, ...$params);
$stmt->execute();
$sales = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$payment_summary = [];
$total_amount = 0;
foreach ($sales as $sale) {
    $pm = $sale['payment_method'] ?: 'Unknown';
    if (!isset($payment_summary[$pm])) {
        $payment_summary[$pm] = ['amount' => 0, 'txns' => 0];
    }
    $payment_summary[$pm]['amount'] += $sale['total_amount'];
    $payment_summary[$pm]['txns']++;
    $total_amount += $sale['total_amount'];
}

$page_title = "Payment Method Report";
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title><?= htmlspecialchars($page_title) ?></title>
<link rel="icon" href="../../images/logo.png" type="image/png" />
<style>
    body {
        margin: 0;
        background: url('../../images/profile.jpg') no-repeat center center fixed;
        background-size: cover;
        font-family: 'Segoe UI', sans-serif;
        color: #eee;
    }
    .content {
        max-width: 1850px;
        margin: 3rem auto;
        padding: 40px 50px;
    }
    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
    }
    h1.page-title {
        color: #ffa500;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 12px;
        font-weight: 700;
        font-size: 2rem;
    }
    h1.page-title img {
        height: 40px;
        width: auto;
    }
    a.back-link {
        color: #ffa500;
        text-decoration: none;
        font-weight: 600;
        border: 1.5px solid #ffa500;
        padding: 6px 14px;
        border-radius: 8px;
    }
    a.back-link:hover {
        background-color: #ffa500;
        color: #222;
    }
    .filter-form {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        margin-bottom: 30px;
    }
    .filter-form input, .filter-form select, .filter-form button {
        padding: 10px 16px;
        border-radius: 8px;
        border: none;
        font-weight: 500;
        min-width: 140px;
        background: rgba(255,255,255,0.15);
        color: #eee;
    }
    .filter-form button {
        background: #ffa500;
        color: #222;
        font-weight: 700;
        cursor: pointer;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        background: rgba(255,255,255,0.07);
        border-radius: 12px;
        overflow: hidden;
        margin-bottom: 40px;
    }
    th, td {
        padding: 14px 18px;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        font-size: 0.95rem;
        text-align: center;
    }
    th {
        background: rgba(198, 109, 8, 0.4);
        color: #ffa500;
        font-weight: 700;
    }
    tbody tr:hover {
        background: rgba(255,165,0,0.1);
    }
    .summary-table td a {
        color: #ffa500;
        text-decoration: none;
        font-weight: 600;
    }
    .summary-table td a:hover {
        text-decoration: underline;
        color: #fff;
    }
</style>
</head>
<body>
<div class="content">

    <div class="page-header">
        <h1 class="page-title">
            <img src="../../images/logo.png" alt="Logo" />
            <?= htmlspecialchars($page_title) ?>
        </h1>
        <a href="reports_dashboard.php" class="back-link">&laquo; Back to Reports Dashboard</a>
    </div>

    <form method="GET" class="filter-form">
        <input type="date" name="date_from" value="<?= htmlspecialchars($date_from) ?>" />
        <input type="date" name="date_to" value="<?= htmlspecialchars($date_to) ?>" />
        <select name="store_id">
            <option value="0">All Stores</option>
            <?php foreach ($stores as $s): ?>
                <option value="<?= $s['id'] ?>" <?= $store_filter == $s['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($s['store_name']) ?>
                </option>
            <?php endforeach; ?>
        </select>
        <select name="cashier_id">
            <option value="0">All Cashiers</option>
            <?php foreach ($cashiers as $c): ?>
                <option value="<?= $c['id'] ?>" <?= $cashier_filter == $c['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($c['name']) ?>
                </option>
            <?php endforeach; ?>
        </select>
        <button type="submit">Filter</button>
    </form>

    <h2 style="color:#ffa500;">Payment Summary</h2>
    <table class="summary-table">
        <thead>
            <tr>
                <th>Payment Method</th>
                <th>Transaction Count</th>
                <th>Total Amount (MWK)</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($payment_summary as $method => $data): ?>
                <tr>
                    <td>
                        <a href="?<?= http_build_query(array_merge($_GET, ['payment_method' => $method])) ?>">
                            <?= htmlspecialchars(ucwords(str_replace('_', ' ', $method))) ?>
                        </a>
                    </td>
                    <td><?= $data['txns'] ?></td>
                    <td><?= number_format($data['amount'], 2) ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <h2 style="color:#ffa500;">Transaction Details<?= $payment_method_filter ? ' - ' . htmlspecialchars(ucwords($payment_method_filter)) : '' ?></h2>
    <table>
        <thead>
            <tr>
                <th>Date</th>
                <th>Txn ID</th>
                <th>Store</th>
                <th>Cashier</th>
                <th>Payment Method</th>
                <th>Amount (MWK)</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($sales)): ?>
                <tr>
                    <td colspan="6" style="color:#ffa500; font-weight: 700; text-align:center;">
                        No transactions found for the selected filters.
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($sales as $sale): ?>
                    <tr>
                        <td><?= htmlspecialchars(date('Y-m-d', strtotime($sale['created_at']))) ?></td>
                        <td><?= htmlspecialchars($sale['receipt_number']) ?></td>
                        <td><?= htmlspecialchars($sale['store_name']) ?></td>
                        <td><?= htmlspecialchars($sale['first_name'] . ' ' . $sale['last_name']) ?></td>
                        <td><?= htmlspecialchars(ucwords(str_replace('_', ' ', $sale['payment_method'] ?: 'Unknown'))) ?></td>
                        <td><?= number_format($sale['total_amount'], 2) ?></td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>

</div>
</body>
</html>
