<?php

require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/config/database.php';
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/auth.php';
require_once __DIR__ . '/../app/helpers/settings.php';
require_once __DIR__ . '/../app/helpers/activity.php';

require_admin();

$pageTitle = 'Payments';
$success = '';
$error = '';

if (isset($_GET['updated'])) {
    $success = 'Payment updated successfully.';
}

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $paymentId = (int) ($_POST['payment_id'] ?? 0);
        $status = $_POST['status'] ?? 'pending';
        $paymentReference = trim($_POST['payment_reference'] ?? '');
        $transactionId = trim($_POST['transaction_id'] ?? '');

        $allowedStatuses = ['pending', 'paid', 'failed', 'refunded', 'cancelled'];

        if ($paymentId <= 0) {
            $error = 'Invalid payment.';
        } elseif (!in_array($status, $allowedStatuses, true)) {
            $error = 'Invalid payment status.';
        } else {
            try {
                $pdo->beginTransaction();

                $stmt = $pdo->prepare("
                    SELECT p.*, o.id AS order_id
                    FROM payments p
                    INNER JOIN orders o ON p.order_id = o.id
                    WHERE p.id = ?
                    LIMIT 1
                ");
                $stmt->execute([$paymentId]);
                $payment = $stmt->fetch();

                if (!$payment) {
                    throw new Exception('Payment not found.');
                }

                $stmt = $pdo->prepare("
                    UPDATE payments
                    SET status = ?,
                        payment_reference = ?,
                        transaction_id = ?
                    WHERE id = ?
                ");

                $stmt->execute([
                    $status,
                    $paymentReference !== '' ? $paymentReference : null,
                    $transactionId !== '' ? $transactionId : null,
                    $paymentId
                ]);

                $orderPaymentStatus = $status === 'paid' ? 'paid' : $status;

                $stmt = $pdo->prepare("
                    UPDATE orders
                    SET payment_status = ?
                    WHERE id = ?
                ");
                $stmt->execute([
                    $orderPaymentStatus,
                    $payment['order_id']
                ]);
                log_admin_activity(
                    'payment_updated',
                    'Payment updated for order ID ' . $payment['order_id'] .
                        ' | Status: ' . $payment['status'] . ' → ' . $status .
                        ' | Reference: ' . ($paymentReference !== '' ? $paymentReference : '-')
                );
                $pdo->commit();

                redirect(ADMIN_URL . '/payments.php?updated=1');
            } catch (Exception $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }

                $error = 'Payment could not be updated: ' . $e->getMessage();
            }
        }
    }
}

$payments = $pdo->query("
    SELECT p.*,
           o.order_number,
           o.customer_email,
           o.customer_phone,
           o.total_amount AS order_total,
           o.payment_status AS order_payment_status,
           o.order_status
    FROM payments p
    INNER JOIN orders o ON p.order_id = o.id
    ORDER BY p.id DESC
")->fetchAll();

require_once __DIR__ . '/includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Payments</h1>
            <div class="admin-user">View manual payment records and prepare for gateway payment tracking.</div>
        </div>
    </div>

    <?php if ($success): ?>
        <div class="admin-alert admin-alert-success"><?= e($success); ?></div>
    <?php endif; ?>

    <?php if ($error): ?>
        <div class="admin-alert admin-alert-error"><?= e($error); ?></div>
    <?php endif; ?>

    <section class="admin-panel">
        <h2>All Payments</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Order</th>
                    <th>Customer</th>
                    <th>Gateway</th>
                    <th>Amount</th>
                    <th>Payment Status</th>
                    <th>Reference</th>
                    <th>Transaction</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$payments): ?>
                    <tr>
                        <td colspan="9">No payments yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($payments as $payment): ?>
                    <tr>
                        <td>
                            <strong><?= e($payment['order_number']); ?></strong><br>
                            <a href="<?= e(ADMIN_URL); ?>/orders.php?view=<?= e($payment['order_id']); ?>">
                                View Order
                            </a>
                        </td>

                        <td>
                            <?= e($payment['customer_email']); ?><br>
                            <small><?= e($payment['customer_phone'] ?? '-'); ?></small>
                        </td>

                        <td><?= e(ucwords(str_replace('_', ' ', $payment['payment_gateway']))); ?></td>

                        <td><?= e(format_price($payment['amount'], $payment['currency_code'])); ?></td>

                        <td>
                            <strong><?= e(ucfirst($payment['status'])); ?></strong><br>
                            <small>Order: <?= e(ucfirst($payment['order_payment_status'])); ?></small>
                        </td>

                        <td><?= e($payment['payment_reference'] ?? '-'); ?></td>

                        <td><?= e($payment['transaction_id'] ?? '-'); ?></td>

                        <td><?= e(date('d M Y', strtotime($payment['created_at']))); ?></td>

                        <td>
                            <form method="POST" style="display:grid; gap:8px; min-width:190px;">
                                <?= csrf_field(); ?>

                                <input type="hidden" name="payment_id" value="<?= e($payment['id']); ?>">

                                <select name="status">
                                    <?php foreach (['pending', 'paid', 'failed', 'refunded', 'cancelled'] as $status): ?>
                                        <option value="<?= e($status); ?>" <?= $payment['status'] === $status ? 'selected' : ''; ?>>
                                            <?= e(ucfirst($status)); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>

                                <input
                                    type="text"
                                    name="payment_reference"
                                    value="<?= e($payment['payment_reference'] ?? ''); ?>"
                                    placeholder="Payment reference">

                                <input
                                    type="text"
                                    name="transaction_id"
                                    value="<?= e($payment['transaction_id'] ?? ''); ?>"
                                    placeholder="Transaction ID">

                                <button type="submit" class="admin-btn">Update</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>