<?php
require_once("../php/db_connect.php");

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION["user_id"]) || ($_SESSION["role"] ?? "") !== "admin") {
    echo "<p>Please log in first.</p>";
    exit;
}

$shop_id = (int)$_SESSION["user_id"];
$filter = $_GET["filter"] ?? "all";

$allowedFilters = ["all", "paid", "partial", "unpaid"];

if (!in_array($filter, $allowedFilters)) {
    $filter = "all";
}

$stmt = $conn->prepare("
    SELECT 
        o.id,
        o.customer_name,
        o.customer_email,
        o.customer_mobile,
        o.total_price,
        o.amount_paid,
        o.remaining_balance,
        o.payment_status,
        o.created_at
    FROM orders o
    WHERE o.shop_id = ?
    ORDER BY o.id DESC
");

$stmt->bind_param("i", $shop_id);
$stmt->execute();
$payments = $stmt->get_result();

function money($amount) {
    return "₱" . number_format((float)$amount, 2);
}

$totalSales = 0;
$totalPaid = 0;
$totalBalance = 0;
$totalRecords = 0;
$fullyPaidCount = 0;
$partialCount = 0;
$unpaidCount = 0;

$paymentRows = [];

if ($payments && $payments->num_rows > 0) {
    while ($row = $payments->fetch_assoc()) {

        $totalRecords++;
        $totalSales += (float)$row["total_price"];
        $totalPaid += (float)$row["amount_paid"];
        $totalBalance += (float)$row["remaining_balance"];

        if ((float)$row["remaining_balance"] <= 0) {
            $fullyPaidCount++;
            $statusKey = "paid";
        } elseif ((float)$row["amount_paid"] > 0) {
            $partialCount++;
            $statusKey = "partial";
        } else {
            $unpaidCount++;
            $statusKey = "unpaid";
        }

        if ($filter === "all" || $filter === $statusKey) {
            $paymentRows[] = $row;
        }
    }
}
?>

<div class="admin-payments-page">

    <div class="payments-header">
        <div>
            <h1>Payment</h1>
            <p>Monitor customer payments, paid amounts, and remaining balances.</p>
        </div>
    </div>

    <div class="payment-stats-grid">

        <div class="payment-stat-card">
            <div class="payment-icon green">
                <i class="fa-solid fa-peso-sign"></i>
            </div>
            <div>
                <p>Total Sales</p>
                <h3><?php echo money($totalSales); ?></h3>
            </div>
        </div>

        <div class="payment-stat-card">
            <div class="payment-icon blue">
                <i class="fa-solid fa-money-bill-wave"></i>
            </div>
            <div>
                <p>Amount Paid</p>
                <h3><?php echo money($totalPaid); ?></h3>
            </div>
        </div>

        <div class="payment-stat-card">
            <div class="payment-icon red">
                <i class="fa-solid fa-wallet"></i>
            </div>
            <div>
                <p>Remaining Balance</p>
                <h3><?php echo money($totalBalance); ?></h3>
            </div>
        </div>

        <div class="payment-stat-card">
            <div class="payment-icon yellow">
                <i class="fa-solid fa-receipt"></i>
            </div>
            <div>
                <p>Total Records</p>
                <h3><?php echo $totalRecords; ?></h3>
            </div>
        </div>

    </div>

  <div class="payment-summary-grid">

    <a href="admin.php?page=payment&filter=all" 
       class="summary-pill all <?php echo $filter === 'all' ? 'active' : ''; ?>">
        All: <strong><?php echo $totalRecords; ?></strong>
    </a>

    <a href="admin.php?page=payment&filter=paid" 
       class="summary-pill paid <?php echo $filter === 'paid' ? 'active' : ''; ?>">
        Fully Paid: <strong><?php echo $fullyPaidCount; ?></strong>
    </a>

    <a href="admin.php?page=payment&filter=partial" 
       class="summary-pill partial <?php echo $filter === 'partial' ? 'active' : ''; ?>">
        Partial: <strong><?php echo $partialCount; ?></strong>
    </a>

    <a href="admin.php?page=payment&filter=unpaid" 
       class="summary-pill unpaid <?php echo $filter === 'unpaid' ? 'active' : ''; ?>">
        Unpaid: <strong><?php echo $unpaidCount; ?></strong>
    </a>

</div>

    <div class="payments-card">

        <div class="payments-card-header">
            <div>
                <h2>Payment Records</h2>
                <p>List of customer payment transactions for your shop.</p>
            </div>
        </div>

        <div class="table-responsive">
            <table class="payments-table">
                <thead>
                    <tr>
                        <th>Order ID</th>
                        <th>Customer</th>
                        <th>Email</th>
                        <th>Contact</th>
                        <th>Total Amount</th>
                        <th>Amount Paid</th>
                        <th>Remaining Balance</th>
                        <th>Status</th>
                        <th>Date Ordered</th>
                    </tr>
                </thead>

                <tbody>
                    <?php if (!empty($paymentRows)): ?>
                        <?php foreach ($paymentRows as $row): ?>
                            <tr>
                                <td>#<?php echo (int)$row["id"]; ?></td>

                                <td class="fw-semibold">
                                    <?php echo htmlspecialchars($row["customer_name"] ?? "N/A"); ?>
                                </td>

                                <td>
                                    <?php echo htmlspecialchars($row["customer_email"] ?? "N/A"); ?>
                                </td>

                                <td>
                                    <?php echo htmlspecialchars($row["customer_mobile"] ?? "N/A"); ?>
                                </td>

                                <td class="fw-bold">
                                    <?php echo money($row["total_price"]); ?>
                                </td>

                                <td class="text-success">
                                    <?php echo money($row["amount_paid"]); ?>
                                </td>

                                <td class="text-danger">
                                    <?php echo money($row["remaining_balance"]); ?>
                                </td>

                                <td>
                                    <?php if ((float)$row["remaining_balance"] <= 0): ?>
                                        <span class="status-badge paid">Fully Paid</span>
                                    <?php elseif ((float)$row["amount_paid"] > 0): ?>
                                        <span class="status-badge partial">Partial</span>
                                    <?php else: ?>
                                        <span class="status-badge unpaid">Unpaid</span>
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <?php
                                    echo !empty($row["created_at"])
                                        ? htmlspecialchars(date("M d, Y", strtotime($row["created_at"])))
                                        : "N/A";
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="9" class="empty-payments">
                                No payment records found.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

    </div>

</div>

<style>
.admin-payments-page {
    width: 100%;
    max-width: 100%;
    overflow-x: hidden;
}

.payments-header {
    margin-bottom: 24px;
}

.payments-header h1 {
    font-size: clamp(28px, 2.4vw, 40px);
    font-weight: 800;
    margin-bottom: 6px;
    color: #111827;
}

.payments-header p {
    color: #64748b;
    margin-bottom: 0;
}

.payment-stats-grid {
    display: grid;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 16px;
    margin-bottom: 18px;
}

.payment-stat-card {
    background: #ffffff;
    border-radius: 20px;
    padding: 22px;
    box-shadow: 0 6px 20px rgba(0,0,0,0.06);
    display: flex;
    align-items: center;
    gap: 16px;
}

.payment-icon {
    width: 54px;
    height: 54px;
    border-radius: 16px;
    display: grid;
    place-items: center;
    font-size: 22px;
    flex-shrink: 0;
}

.payment-icon.green {
    background: #dcfce7;
    color: #15803d;
}

.payment-icon.blue {
    background: #dbeafe;
    color: #2563eb;
}

.payment-icon.red {
    background: #fee2e2;
    color: #dc2626;
}

.payment-icon.yellow {
    background: #fef3c7;
    color: #b45309;
}

.payment-stat-card p {
    margin: 0 0 4px;
    color: #64748b;
    font-size: 14px;
}

.payment-stat-card h3 {
    margin: 0;
    font-size: 25px;
    font-weight: 800;
    color: #111827;
}

.payment-summary-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 24px;
}

.summary-pill {
    padding: 10px 16px;
    border-radius: 999px;
    font-size: 14px;
    font-weight: 700;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    border: 2px solid transparent;
    transition: 0.2s ease;
}

.summary-pill:hover {
    transform: translateY(-1px);
    text-decoration: none;
}

.summary-pill.all {
    background: #e0f2fe;
    color: #0369a1;
}

.summary-pill.paid {
    background: #dcfce7;
    color: #15803d;
}

.summary-pill.partial {
    background: #fef3c7;
    color: #b45309;
}

.summary-pill.unpaid {
    background: #fee2e2;
    color: #b91c1c;
}

.summary-pill.active {
    border-color: #111827;
    box-shadow: 0 4px 12px rgba(0,0,0,0.12);
}

.payments-card {
    background: #ffffff;
    border-radius: 22px;
    padding: 24px;
    box-shadow: 0 6px 20px rgba(0,0,0,0.06);
    overflow: hidden;
}

.payments-card-header {
    margin-bottom: 18px;
}

.payments-card-header h2 {
    font-size: 24px;
    font-weight: 800;
    margin-bottom: 4px;
}

.payments-card-header p {
    color: #64748b;
    margin-bottom: 0;
}

.table-responsive {
    width: 100%;
    overflow-x: auto;
}

.payments-table {
    width: 100%;
    min-width: 1050px;
    border-collapse: collapse;
}

.payments-table th {
    background: #f8fafc;
    padding: 16px;
    font-weight: 700;
    color: #111827;
    border-bottom: 1px solid #e5e7eb;
    white-space: nowrap;
}

.payments-table td {
    padding: 16px;
    border-bottom: 1px solid #f1f5f9;
    color: #1f2937;
    white-space: nowrap;
    vertical-align: middle;
}

.text-success {
    color: #16a34a !important;
    font-weight: 700;
}

.text-danger {
    color: #dc2626 !important;
    font-weight: 700;
}

.status-badge {
    padding: 7px 13px;
    border-radius: 999px;
    font-size: 13px;
    font-weight: 700;
    display: inline-block;
}

.status-badge.paid {
    background: #dcfce7;
    color: #15803d;
}

.status-badge.partial {
    background: #fef3c7;
    color: #b45309;
}

.status-badge.unpaid {
    background: #fee2e2;
    color: #b91c1c;
}

.empty-payments {
    text-align: center;
    padding: 40px;
    color: #64748b;
}

@media (max-width: 1200px) {
    .payment-stats-grid {
        grid-template-columns: repeat(2, minmax(0, 1fr));
    }
}

@media (max-width: 768px) {
    .payment-stats-grid {
        grid-template-columns: 1fr;
    }

    .payments-card {
        padding: 18px;
        border-radius: 18px;
    }

    .payment-stat-card {
        padding: 18px;
    }

    .payments-table {
        min-width: 900px;
    }
}
</style>