<?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_admin();

$pageTitle = 'Loyalty & Referrals';
$success = '';
$error = '';

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

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

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $action = $_POST['action'] ?? '';

        if ($action === 'adjust_points') {
            $customerId = (int) ($_POST['customer_id'] ?? 0);
            $points = (int) ($_POST['points'] ?? 0);
            $adjustmentType = $_POST['adjustment_type'] ?? 'add';
            $description = trim($_POST['description'] ?? '');

            if ($customerId <= 0) {
                $error = 'Invalid customer.';
            } elseif ($points <= 0) {
                $error = 'Points must be greater than zero.';
            } elseif (!in_array($adjustmentType, ['add', 'deduct'], true)) {
                $error = 'Invalid adjustment type.';
            } else {
                try {
                    $pdo->beginTransaction();

                    $stmt = $pdo->prepare("
                        SELECT id
                        FROM customers
                        WHERE id = ?
                        LIMIT 1
                    ");
                    $stmt->execute([$customerId]);
                    $customer = $stmt->fetch();

                    if (!$customer) {
                        throw new Exception('Customer not found.');
                    }

                    $stmt = $pdo->prepare("
                        SELECT *
                        FROM customer_loyalty
                        WHERE customer_id = ?
                        LIMIT 1
                    ");
                    $stmt->execute([$customerId]);
                    $loyalty = $stmt->fetch();

                    if (!$loyalty) {
                        $stmt = $pdo->prepare("
                            INSERT INTO customer_loyalty (
                                customer_id,
                                points_balance,
                                lifetime_points
                            ) VALUES (?, 0, 0)
                        ");
                        $stmt->execute([$customerId]);

                        $loyalty = [
                            'points_balance' => 0,
                            'lifetime_points' => 0
                        ];
                    }

                    $currentBalance = (int) $loyalty['points_balance'];
                    $currentLifetime = (int) $loyalty['lifetime_points'];

                    if ($adjustmentType === 'add') {
                        $newBalance = $currentBalance + $points;
                        $newLifetime = $currentLifetime + $points;
                        $transactionPoints = $points;
                        $transactionType = 'adjustment';
                        $transactionDescription = $description !== ''
                            ? $description
                            : 'Manual loyalty points added by admin';
                    } else {
                        $newBalance = max(0, $currentBalance - $points);
                        $newLifetime = $currentLifetime;
                        $transactionPoints = -$points;
                        $transactionType = 'adjustment';
                        $transactionDescription = $description !== ''
                            ? $description
                            : 'Manual loyalty points deducted by admin';
                    }

                    $stmt = $pdo->prepare("
                        UPDATE customer_loyalty
                        SET points_balance = ?,
                            lifetime_points = ?
                        WHERE customer_id = ?
                    ");

                    $stmt->execute([
                        $newBalance,
                        $newLifetime,
                        $customerId
                    ]);

                    $stmt = $pdo->prepare("
                        INSERT INTO loyalty_transactions (
                            customer_id,
                            order_id,
                            transaction_type,
                            points,
                            description
                        ) VALUES (?, NULL, ?, ?, ?)
                    ");

                    $stmt->execute([
                        $customerId,
                        $transactionType,
                        $transactionPoints,
                        $transactionDescription
                    ]);

                    $pdo->commit();

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

                    $error = 'Could not update loyalty points: ' . $e->getMessage();
                }
            }
        }

        if ($action === 'update_referral_reward') {
            $rewardId = (int) ($_POST['reward_id'] ?? 0);
            $status = $_POST['status'] ?? 'pending';

            if ($rewardId <= 0) {
                $error = 'Invalid reward.';
            } elseif (!in_array($status, ['pending', 'issued', 'used', 'cancelled'], true)) {
                $error = 'Invalid reward status.';
            } else {
                $stmt = $pdo->prepare("
                    UPDATE referral_rewards
                    SET status = ?,
                        issued_at = CASE
                            WHEN ? = 'issued' AND issued_at IS NULL THEN NOW()
                            ELSE issued_at
                        END
                    WHERE id = ?
                ");

                $stmt->execute([
                    $status,
                    $status,
                    $rewardId
                ]);

                redirect(ADMIN_URL . '/loyalty.php?reward_updated=1');
            }
        }

        if ($action === 'update_referral_status') {
            $referralId = (int) ($_POST['referral_id'] ?? 0);
            $rewardStatus = $_POST['reward_status'] ?? 'pending';

            if ($referralId <= 0) {
                $error = 'Invalid referral.';
            } elseif (!in_array($rewardStatus, ['pending', 'approved', 'rejected', 'paid'], true)) {
                $error = 'Invalid referral status.';
            } else {
                $stmt = $pdo->prepare("
                    UPDATE referrals
                    SET reward_status = ?
                    WHERE id = ?
                ");

                $stmt->execute([
                    $rewardStatus,
                    $referralId
                ]);

                redirect(ADMIN_URL . '/loyalty.php?reward_updated=1');
            }
        }
    }
}

$loyaltyCustomers = $pdo->query("
    SELECT 
        c.id AS customer_id,
        c.first_name,
        c.last_name,
        c.email,
        c.referral_code,
        c.status,
        COALESCE(cl.points_balance, 0) AS points_balance,
        COALESCE(cl.lifetime_points, 0) AS lifetime_points,
        cl.updated_at
    FROM customers c
    LEFT JOIN customer_loyalty cl ON c.id = cl.customer_id
    ORDER BY points_balance DESC, lifetime_points DESC, c.id DESC
")->fetchAll();

$transactions = $pdo->query("
    SELECT 
        lt.*,
        c.first_name,
        c.last_name,
        c.email,
        o.order_number
    FROM loyalty_transactions lt
    LEFT JOIN customers c ON lt.customer_id = c.id
    LEFT JOIN orders o ON lt.order_id = o.id
    ORDER BY lt.id DESC
    LIMIT 80
")->fetchAll();

$referrals = $pdo->query("
    SELECT 
        r.*,
        referrer.first_name AS referrer_first_name,
        referrer.last_name AS referrer_last_name,
        referrer.email AS referrer_email,
        referred.first_name AS referred_first_name,
        referred.last_name AS referred_last_name,
        referred.email AS referred_email
    FROM referrals r
    LEFT JOIN customers referrer ON r.referrer_customer_id = referrer.id
    LEFT JOIN customers referred ON r.referred_customer_id = referred.id
    ORDER BY r.id DESC
")->fetchAll();

$referralRewards = $pdo->query("
    SELECT 
        rr.*,
        r.referral_code,
        referrer.first_name AS referrer_first_name,
        referrer.last_name AS referrer_last_name,
        referrer.email AS referrer_email,
        referred.first_name AS referred_first_name,
        referred.last_name AS referred_last_name,
        referred.email AS referred_email
    FROM referral_rewards rr
    INNER JOIN referrals r ON rr.referral_id = r.id
    LEFT JOIN customers referrer ON r.referrer_customer_id = referrer.id
    LEFT JOIN customers referred ON r.referred_customer_id = referred.id
    ORDER BY rr.id DESC
")->fetchAll();

$totalPointsBalance = $pdo->query("
    SELECT COALESCE(SUM(points_balance), 0)
    FROM customer_loyalty
")->fetchColumn();

$totalLifetimePoints = $pdo->query("
    SELECT COALESCE(SUM(lifetime_points), 0)
    FROM customer_loyalty
")->fetchColumn();

$totalReferrals = $pdo->query("
    SELECT COUNT(*)
    FROM referrals
")->fetchColumn();

$approvedReferrals = $pdo->query("
    SELECT COUNT(*)
    FROM referrals
    WHERE reward_status = 'approved'
")->fetchColumn();

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

<main class="admin-main">
    <div class="admin-topbar">
        <div>
            <h1>Loyalty & Referrals</h1>
            <div class="admin-user">Manage customer loyalty points, transactions, referral codes, and rewards.</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-cards">
        <div class="admin-card">
            <span>Total Active Points</span>
            <strong><?= e((int)$totalPointsBalance); ?></strong>
        </div>

        <div class="admin-card">
            <span>Lifetime Points</span>
            <strong><?= e((int)$totalLifetimePoints); ?></strong>
        </div>

        <div class="admin-card">
            <span>Total Referrals</span>
            <strong><?= e((int)$totalReferrals); ?></strong>
        </div>

        <div class="admin-card">
            <span>Approved Referrals</span>
            <strong><?= e((int)$approvedReferrals); ?></strong>
        </div>
    </section>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2>Manual Points Adjustment</h2>

        <form method="POST">
            <?= csrf_field(); ?>
            <input type="hidden" name="action" value="adjust_points">

            <div class="admin-form-grid">
                <div class="admin-field">
                    <label>Customer</label>
                    <select name="customer_id" required>
                        <option value="">Select Customer</option>
                        <?php foreach ($loyaltyCustomers as $customer): ?>
                            <option value="<?= e($customer['customer_id']); ?>">
                                <?= e(trim($customer['first_name'] . ' ' . $customer['last_name'])); ?>
                                —
                                <?= e($customer['email']); ?>
                                —
                                <?= e($customer['points_balance']); ?> points
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="admin-field">
                    <label>Adjustment Type</label>
                    <select name="adjustment_type" required>
                        <option value="add">Add Points</option>
                        <option value="deduct">Deduct Points</option>
                    </select>
                </div>

                <div class="admin-field">
                    <label>Points</label>
                    <input type="number" name="points" min="1" required>
                </div>

                <div class="admin-field">
                    <label>Description</label>
                    <input type="text" name="description" placeholder="Example: Bonus points for campaign">
                </div>
            </div>

            <button type="submit" class="admin-btn">Apply Adjustment</button>
        </form>
    </section>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2>Customer Loyalty Balances</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Customer</th>
                    <th>Email</th>
                    <th>Referral Code</th>
                    <th>Points Balance</th>
                    <th>Lifetime Points</th>
                    <th>Status</th>
                    <th>Updated</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$loyaltyCustomers): ?>
                    <tr>
                        <td colspan="7">No customers found.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($loyaltyCustomers as $customer): ?>
                    <tr>
                        <td>
                            <strong><?= e(trim($customer['first_name'] . ' ' . $customer['last_name'])); ?></strong>
                        </td>
                        <td><?= e($customer['email']); ?></td>
                        <td><?= e($customer['referral_code'] ?? '-'); ?></td>
                        <td><strong><?= e((int)$customer['points_balance']); ?></strong></td>
                        <td><?= e((int)$customer['lifetime_points']); ?></td>
                        <td><?= e(ucfirst($customer['status'])); ?></td>
                        <td>
                            <?= !empty($customer['updated_at'])
                                ? e(date('d M Y, h:i A', strtotime($customer['updated_at'])))
                                : '-'; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2>Loyalty Transaction History</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Customer</th>
                    <th>Order</th>
                    <th>Type</th>
                    <th>Points</th>
                    <th>Description</th>
                    <th>Date</th>
                </tr>
            </thead>

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

                <?php foreach ($transactions as $transaction): ?>
                    <tr>
                        <td>
                            <strong>
                                <?= e(trim(($transaction['first_name'] ?? '') . ' ' . ($transaction['last_name'] ?? '')) ?: 'Customer'); ?>
                            </strong><br>
                            <small><?= e($transaction['email'] ?? '-'); ?></small>
                        </td>

                        <td><?= e($transaction['order_number'] ?? '-'); ?></td>

                        <td><?= e(ucfirst($transaction['transaction_type'])); ?></td>

                        <td>
                            <strong><?= e((int)$transaction['points']); ?></strong>
                        </td>

                        <td><?= e($transaction['description'] ?? '-'); ?></td>

                        <td><?= e(date('d M Y, h:i A', strtotime($transaction['created_at']))); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>

    <section class="admin-panel" style="margin-bottom:24px;">
        <h2>Referrals</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Referral Code</th>
                    <th>Referrer</th>
                    <th>Referred Customer</th>
                    <th>Reward Status</th>
                    <th>Date</th>
                    <th>Action</th>
                </tr>
            </thead>

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

                <?php foreach ($referrals as $referral): ?>
                    <tr>
                        <td><strong><?= e($referral['referral_code']); ?></strong></td>

                        <td>
                            <?= e(trim(($referral['referrer_first_name'] ?? '') . ' ' . ($referral['referrer_last_name'] ?? '')) ?: 'Referrer'); ?><br>
                            <small><?= e($referral['referrer_email'] ?? '-'); ?></small>
                        </td>

                        <td>
                            <?php if (!empty($referral['referred_customer_id'])): ?>
                                <?= e(trim(($referral['referred_first_name'] ?? '') . ' ' . ($referral['referred_last_name'] ?? '')) ?: 'Customer'); ?><br>
                                <small><?= e($referral['referred_email'] ?? '-'); ?></small>
                            <?php else: ?>
                                Not registered yet
                            <?php endif; ?>
                        </td>

                        <td><?= e(ucfirst($referral['reward_status'])); ?></td>

                        <td><?= e(date('d M Y, h:i A', strtotime($referral['created_at']))); ?></td>

                        <td>
                            <form method="POST" style="display:grid; gap:8px; min-width:160px;">
                                <?= csrf_field(); ?>
                                <input type="hidden" name="action" value="update_referral_status">
                                <input type="hidden" name="referral_id" value="<?= e($referral['id']); ?>">

                                <select name="reward_status">
                                    <?php foreach (['pending', 'approved', 'rejected', 'paid'] as $status): ?>
                                        <option value="<?= e($status); ?>" <?= $referral['reward_status'] === $status ? 'selected' : ''; ?>>
                                            <?= e(ucfirst($status)); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>

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

    <section class="admin-panel">
        <h2>Referral Rewards</h2>

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Referral Code</th>
                    <th>Referrer</th>
                    <th>Reward</th>
                    <th>Issued At</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$referralRewards): ?>
                    <tr>
                        <td colspan="6">No referral rewards yet.</td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($referralRewards as $reward): ?>
                    <tr>
                        <td><strong><?= e($reward['referral_code']); ?></strong></td>

                        <td>
                            <?= e(trim(($reward['referrer_first_name'] ?? '') . ' ' . ($reward['referrer_last_name'] ?? '')) ?: 'Referrer'); ?><br>
                            <small><?= e($reward['referrer_email'] ?? '-'); ?></small>
                        </td>

                        <td>
                            <?= e(ucfirst(str_replace('_', ' ', $reward['reward_type']))); ?>
                            —
                            <?php if ($reward['reward_type'] === 'points'): ?>
                                <?= e((int)$reward['reward_value']); ?> points
                            <?php else: ?>
                                <?= e(format_price($reward['reward_value'])); ?>
                            <?php endif; ?>
                        </td>

                        <td>
                            <?= !empty($reward['issued_at'])
                                ? e(date('d M Y, h:i A', strtotime($reward['issued_at'])))
                                : '-'; ?>
                        </td>

                        <td><?= e(ucfirst($reward['status'])); ?></td>

                        <td>
                            <form method="POST" style="display:grid; gap:8px; min-width:160px;">
                                <?= csrf_field(); ?>
                                <input type="hidden" name="action" value="update_referral_reward">
                                <input type="hidden" name="reward_id" value="<?= e($reward['id']); ?>">

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

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

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