<?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 = 'Customers';
$success = '';
$error = '';

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

$customerId = isset($_GET['view']) ? (int) $_GET['view'] : 0;

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $updateCustomerId = (int) ($_POST['customer_id'] ?? 0);
        $status = $_POST['status'] ?? 'active';

        $allowedStatuses = ['active', 'inactive', 'blocked'];

        if ($updateCustomerId <= 0) {
            $error = 'Invalid customer.';
        } elseif (!in_array($status, $allowedStatuses, true)) {
            $error = 'Invalid customer status.';
        } else {
            $stmt = $pdo->prepare("
                UPDATE customers
                SET status = ?
                WHERE id = ?
            ");
            $stmt->execute([$status, $updateCustomerId]);

            redirect(ADMIN_URL . '/customers.php?view=' . $updateCustomerId . '&updated=1');
        }
    }
}

if ($customerId > 0) {
    $stmt = $pdo->prepare("
        SELECT c.*,
               cl.points_balance,
               cl.lifetime_points,
               ref.email AS referred_by_email
        FROM customers c
        LEFT JOIN customer_loyalty cl ON c.id = cl.customer_id
        LEFT JOIN customers ref ON c.referred_by_customer_id = ref.id
        WHERE c.id = ?
        LIMIT 1
    ");
    $stmt->execute([$customerId]);
    $customer = $stmt->fetch();

    if (!$customer) {
        redirect(ADMIN_URL . '/customers.php');
    }

    $stmt = $pdo->prepare("
        SELECT *
        FROM customer_addresses
        WHERE customer_id = ?
        ORDER BY is_default DESC, id DESC
    ");
    $stmt->execute([$customerId]);
    $addresses = $stmt->fetchAll();

    $stmt = $pdo->prepare("
        SELECT *
        FROM orders
        WHERE customer_id = ? OR customer_email = ?
        ORDER BY id DESC
    ");
    $stmt->execute([$customerId, $customer['email']]);
    $orders = $stmt->fetchAll();

    $stmt = $pdo->prepare("
        SELECT wi.created_at, p.product_name, p.slug
        FROM wishlist_items wi
        INNER JOIN products p ON wi.product_id = p.id
        WHERE wi.customer_id = ?
        ORDER BY wi.id DESC
    ");
    $stmt->execute([$customerId]);
    $wishlistItems = $stmt->fetchAll();

    $stmt = $pdo->prepare("
        SELECT *
        FROM loyalty_transactions
        WHERE customer_id = ?
        ORDER BY id DESC
        LIMIT 20
    ");
    $stmt->execute([$customerId]);
    $loyaltyTransactions = $stmt->fetchAll();

    $stmt = $pdo->prepare("
        SELECT r.*, rc.email AS referred_customer_email
        FROM referrals r
        LEFT JOIN customers rc ON r.referred_customer_id = rc.id
        WHERE r.referrer_customer_id = ?
        ORDER BY r.id DESC
    ");
    $stmt->execute([$customerId]);
    $referrals = $stmt->fetchAll();

    $totalSpent = 0;
    foreach ($orders as $order) {
        if ($order['payment_status'] === 'paid') {
            $totalSpent += (float) $order['total_amount'];
        }
    }

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

    <main class="admin-main">
        <div class="admin-topbar">
            <div>
                <h1><?= e(trim($customer['first_name'] . ' ' . $customer['last_name'])); ?></h1>
                <div class="admin-user"><?= e($customer['email']); ?></div>
            </div>

            <a href="<?= e(ADMIN_URL); ?>/customers.php" class="admin-btn admin-btn-light">Back to Customers</a>
        </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 Orders</span>
                <strong><?= e(count($orders)); ?></strong>
            </div>

            <div class="admin-card">
                <span>Total Spent</span>
                <strong><?= e(format_price($totalSpent)); ?></strong>
            </div>

            <div class="admin-card">
                <span>Loyalty Points</span>
                <strong><?= e($customer['points_balance'] ?? 0); ?></strong>
            </div>

            <div class="admin-card">
                <span>Wishlist Items</span>
                <strong><?= e(count($wishlistItems)); ?></strong>
            </div>
        </section>

        <div style="display:grid; grid-template-columns: 1fr 360px; gap:24px; align-items:start;">
            <div>
                <section class="admin-panel" style="margin-bottom:24px;">
                    <h2>Customer Details</h2>

                    <div class="admin-form-grid">
                        <div>
                            <p>
                                <strong>Name:</strong> <?= e(trim($customer['first_name'] . ' ' . $customer['last_name'])); ?><br>
                                <strong>Email:</strong> <?= e($customer['email']); ?><br>
                                <strong>Phone:</strong> <?= e($customer['phone'] ?? '-'); ?><br>
                                <strong>Google Login:</strong> <?= !empty($customer['google_id']) ? 'Connected' : 'Not connected'; ?><br>
                                <strong>Email Verified:</strong> <?= !empty($customer['email_verified_at']) ? e(date('d M Y', strtotime($customer['email_verified_at']))) : 'Not verified'; ?>
                            </p>
                        </div>

                        <div>
                            <p>
                                <strong>Status:</strong> <?= e(ucfirst($customer['status'])); ?><br>
                                <strong>2FA:</strong> <?= !empty($customer['two_factor_enabled']) ? 'Enabled' : 'Disabled'; ?><br>
                                <strong>Referral Code:</strong> <?= e($customer['referral_code'] ?? '-'); ?><br>
                                <strong>Referred By:</strong> <?= e($customer['referred_by_email'] ?? '-'); ?><br>
                                <strong>Joined:</strong> <?= e(date('d M Y', strtotime($customer['created_at']))); ?>
                            </p>
                        </div>
                    </div>
                </section>

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

                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th>Type</th>
                                <th>Name</th>
                                <th>Address</th>
                                <th>Default</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if (!$addresses): ?>
                                <tr>
                                    <td colspan="4">No addresses saved.</td>
                                </tr>
                            <?php endif; ?>

                            <?php foreach ($addresses as $address): ?>
                                <tr>
                                    <td><?= e(ucfirst($address['address_type'])); ?></td>
                                    <td>
                                        <?= e($address['full_name']); ?><br>
                                        <small><?= e($address['phone'] ?? '-'); ?></small>
                                    </td>
                                    <td>
                                        <?= e($address['address_line_1']); ?><br>
                                        <?php if (!empty($address['address_line_2'])): ?>
                                            <?= e($address['address_line_2']); ?><br>
                                        <?php endif; ?>
                                        <?= e($address['city']); ?>,
                                        <?= e($address['state_region'] ?? ''); ?>
                                        <?= e($address['postal_code'] ?? ''); ?><br>
                                        <?= e($address['country']); ?>
                                    </td>
                                    <td><?= $address['is_default'] ? 'Yes' : 'No'; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </section>

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

                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th>Order</th>
                                <th>Total</th>
                                <th>Payment</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Action</th>
                            </tr>
                        </thead>

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

                            <?php foreach ($orders as $order): ?>
                                <tr>
                                    <td><?= e($order['order_number']); ?></td>
                                    <td><?= e(format_price($order['total_amount'], $order['currency_code'])); ?></td>
                                    <td><?= e(ucfirst($order['payment_status'])); ?></td>
                                    <td><?= e(ucfirst($order['order_status'])); ?></td>
                                    <td><?= e(date('d M Y', strtotime($order['created_at']))); ?></td>
                                    <td>
                                        <a class="admin-btn admin-btn-light" href="<?= e(ADMIN_URL); ?>/orders.php?view=<?= e($order['id']); ?>">View</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </section>

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

                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th>Product</th>
                                <th>Added</th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php if (!$wishlistItems): ?>
                                <tr>
                                    <td colspan="2">No wishlist items.</td>
                                </tr>
                            <?php endif; ?>

                            <?php foreach ($wishlistItems as $item): ?>
                                <tr>
                                    <td>
                                        <a href="<?= e(BASE_URL); ?>/public/product.php?slug=<?= e($item['slug']); ?>" target="_blank">
                                            <?= e($item['product_name']); ?>
                                        </a>
                                    </td>
                                    <td><?= e(date('d M Y', strtotime($item['created_at']))); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </section>

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

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

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

                            <?php foreach ($loyaltyTransactions as $transaction): ?>
                                <tr>
                                    <td><?= e(ucfirst($transaction['transaction_type'])); ?></td>
                                    <td><?= e($transaction['points']); ?></td>
                                    <td><?= e($transaction['description'] ?? '-'); ?></td>
                                    <td><?= e(date('d M Y', strtotime($transaction['created_at']))); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </section>

                <section class="admin-panel">
                    <h2>Referrals</h2>

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

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

                            <?php foreach ($referrals as $referral): ?>
                                <tr>
                                    <td><?= e($referral['referral_code']); ?></td>
                                    <td><?= e($referral['referred_customer_email'] ?? '-'); ?></td>
                                    <td><?= e(ucfirst($referral['reward_status'])); ?></td>
                                    <td><?= e(date('d M Y', strtotime($referral['created_at']))); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </section>
            </div>

            <aside class="admin-panel">
                <h2>Update Customer</h2>

                <form method="POST">
                    <?= csrf_field(); ?>

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

                    <div class="admin-field">
                        <label>Status</label>
                        <select name="status">
                            <?php foreach (['active', 'inactive', 'blocked'] as $status): ?>
                                <option value="<?= e($status); ?>" <?= $customer['status'] === $status ? 'selected' : ''; ?>>
                                    <?= e(ucfirst($status)); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <button type="submit" class="admin-btn">Update Customer</button>
                </form>
            </aside>
        </div>
    </main>

    <?php
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

$customers = $pdo->query("
    SELECT c.*,
           cl.points_balance,
           COUNT(DISTINCT o.id) AS total_orders,
           COALESCE(SUM(CASE WHEN o.payment_status = 'paid' THEN o.total_amount ELSE 0 END), 0) AS total_spent
    FROM customers c
    LEFT JOIN customer_loyalty cl ON c.id = cl.customer_id
    LEFT JOIN orders o ON o.customer_id = c.id OR o.customer_email = c.email
    GROUP BY c.id
    ORDER BY c.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>Customers</h1>
            <div class="admin-user">View registered customers, orders, loyalty, referrals, and wishlist activity.</div>
        </div>
    </div>

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

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

        <table class="admin-table">
            <thead>
                <tr>
                    <th>Customer</th>
                    <th>Contact</th>
                    <th>Orders</th>
                    <th>Total Spent</th>
                    <th>Loyalty</th>
                    <th>Referral</th>
                    <th>Status</th>
                    <th>Joined</th>
                    <th>Action</th>
                </tr>
            </thead>

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

                <?php foreach ($customers as $customer): ?>
                    <tr>
                        <td>
                            <strong><?= e(trim($customer['first_name'] . ' ' . $customer['last_name'])); ?></strong><br>
                            <small>ID: <?= e($customer['id']); ?></small>
                        </td>

                        <td>
                            <?= e($customer['email']); ?><br>
                            <small><?= e($customer['phone'] ?? '-'); ?></small>
                        </td>

                        <td><?= e($customer['total_orders']); ?></td>
                        <td><?= e(format_price($customer['total_spent'])); ?></td>
                        <td><?= e($customer['points_balance'] ?? 0); ?> pts</td>
                        <td><?= e($customer['referral_code'] ?? '-'); ?></td>
                        <td><?= e(ucfirst($customer['status'])); ?></td>
                        <td><?= e(date('d M Y', strtotime($customer['created_at']))); ?></td>
                        <td>
                            <a class="admin-btn admin-btn-light" href="<?= e(ADMIN_URL); ?>/customers.php?view=<?= e($customer['id']); ?>">View</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</main>

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