<?php
// ============================================================
//  Admin: business claim approvals
// ============================================================
//
//  Pending claims from claim-business.php land here. Admin can:
//    - Approve: attach the listing to an existing or new member
//    - Reject: mark the claim rejected (admin should contact the claimant)
//
//  Approval flow:
//    1. Look up the claim's email in `members` table
//    2. If a member exists, assign listings.member_id to them
//    3. If not, we don't auto-create — safer to reject + tell the
//       claimant to sign up as a new member first, then claim
//
// ============================================================

$page_title = 'Business claims';
require __DIR__ . '/_guard.php';
require_once __DIR__ . '/../includes/mail.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $claim_id = (int)($_POST['claim_id'] ?? 0);
    $action   = $_POST['do'] ?? '';

    $claim = db_row('SELECT * FROM business_claims WHERE id = :id', ['id' => $claim_id]);

    if (!$claim || $claim['status'] !== 'pending') {
        header('Location: claims.php?error=invalid'); exit;
    }

    if ($action === 'approve') {
        // Find the member with this email
        $member = db_row('SELECT * FROM members WHERE email = :e', ['e' => $claim['email']]);

        if (!$member) {
            // Don't auto-create a member — mark the claim as rejected with a note.
            db_exec(
                "UPDATE business_claims SET status = 'rejected', reviewed_at = NOW()
                 WHERE id = :id",
                ['id' => $claim_id]
            );
            mail_send(
                $claim['email'],
                'Buy Local claim — next steps',
                "Hi,\n\n" .
                "We couldn't approve your claim on that listing because you don't yet " .
                "have a Buy Local Lowveld account on this email address.\n\n" .
                "To complete the claim, please sign up as a new member here:\n\n" .
                "  " . SITE_URL . "/become-member.php\n\n" .
                "Use the same email address (" . $claim['email'] . "), and we'll merge " .
                "the listing to your account within 1 business day.\n\n" .
                "— The Buy Local team\n"
            );
            header('Location: claims.php?msg=needs_signup'); exit;
        }

        // Attach the listing to the member
        db_exec(
            'UPDATE listings SET member_id = :m WHERE id = :l',
            ['m' => $member['id'], 'l' => $claim['listing_id']]
        );
        db_exec(
            "UPDATE business_claims SET status = 'approved', reviewed_at = NOW()
             WHERE id = :id",
            ['id' => $claim_id]
        );

        // Promote pending member to active if that's what they were
        if ($member['status'] === 'pending') {
            db_exec(
                "UPDATE members SET status = 'active' WHERE id = :id",
                ['id' => $member['id']]
            );
        }

        // Send the approval email via templated email system
        require_once __DIR__ . '/../includes/mailer.php';
        $listing = db_row('SELECT name FROM listings WHERE id = :id', ['id' => $claim['listing_id']]);
        email_enqueue('claim_approved', $claim['email'],
            trim($claim['first_name'] . ' ' . ($claim['last_name'] ?? '')),
            [
                'first_name'    => $claim['first_name'],
                'business_name' => $listing['name'] ?? '',
            ]
        );

        header('Location: claims.php?msg=approved'); exit;
    }

    if ($action === 'reject') {
        $reason = trim($_POST['reason'] ?? '');
        db_exec(
            "UPDATE business_claims SET status = 'rejected', reviewed_at = NOW()
             WHERE id = :id",
            ['id' => $claim_id]
        );

        if ($reason) {
            mail_send(
                $claim['email'],
                'About your Buy Local listing claim',
                "Hi {$claim['first_name']},\n\n" .
                "Thanks for your claim request. After review we're unable to approve it:\n\n" .
                "  $reason\n\n" .
                "If you think there's been a mistake, reply to this email with additional " .
                "proof of ownership and we'll take another look.\n\n" .
                "— The Buy Local team\n"
            );
        }

        header('Location: claims.php?msg=rejected'); exit;
    }
}

// Filter
$filter = $_GET['filter'] ?? 'pending';
$where  = "WHERE 1=1";
if ($filter === 'pending')  $where .= " AND c.status = 'pending'";
if ($filter === 'approved') $where .= " AND c.status = 'approved'";
if ($filter === 'rejected') $where .= " AND c.status = 'rejected'";

$claims = db_all(
    "SELECT c.*, l.name AS listing_name, l.address AS listing_address,
            l.category_slug, l.member_id AS listing_member_id
       FROM business_claims c
       JOIN listings l ON l.id = c.listing_id
       $where
       ORDER BY c.created_at DESC
       LIMIT 200"
);

$counts = [
    'pending'  => (int)db_value("SELECT COUNT(*) FROM business_claims WHERE status='pending'"),
    'approved' => (int)db_value("SELECT COUNT(*) FROM business_claims WHERE status='approved'"),
    'rejected' => (int)db_value("SELECT COUNT(*) FROM business_claims WHERE status='rejected'"),
];
?>

<section class="section">
    <div class="container">
        <h1>Business claims</h1>

        <?php
        $msg = $_GET['msg'] ?? '';
        if ($msg === 'approved'): ?>
            <div class="alert alert-success" data-autohide>
                Claim approved. Listing attached to the member. Email notification sent.
            </div>
        <?php elseif ($msg === 'rejected'): ?>
            <div class="alert alert-info" data-autohide>Claim rejected. Email sent to the claimant.</div>
        <?php elseif ($msg === 'needs_signup'): ?>
            <div class="alert alert-info" data-autohide>
                Claimant doesn't have a member account yet. They've been emailed sign-up instructions.
            </div>
        <?php endif; ?>

        <div class="nav" style="margin-bottom:1.5rem;">
            <a href="?filter=pending"  class="<?= $filter==='pending'?'current':'' ?>">Pending (<?= $counts['pending'] ?>)</a>
            <a href="?filter=approved" class="<?= $filter==='approved'?'current':'' ?>">Approved (<?= $counts['approved'] ?>)</a>
            <a href="?filter=rejected" class="<?= $filter==='rejected'?'current':'' ?>">Rejected (<?= $counts['rejected'] ?>)</a>
        </div>

        <?php if (empty($claims)): ?>
            <div class="card"><p class="muted">No claims in this bucket.</p></div>
        <?php else: ?>
            <?php foreach ($claims as $c): ?>
                <div class="card mb-3">
                    <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:1rem;">
                        <div>
                            <h3 style="margin:0;">
                                <?= htmlspecialchars($c['listing_name']) ?>
                                <span class="muted" style="font-size:.9rem;font-weight:400;">
                                    &middot; <?= htmlspecialchars($c['listing_address'] ?? '') ?>
                                </span>
                            </h3>
                            <p class="muted" style="margin:.2rem 0;">
                                Submitted <?= date('j M Y H:i', strtotime($c['created_at'])) ?>
                            </p>
                        </div>
                        <span class="tag tag-<?= $c['status']==='pending'?'err':($c['status']==='approved'?'ok':'err') ?>">
                            <?= htmlspecialchars($c['status']) ?>
                        </span>
                    </div>

                    <div class="grid grid-2 mt-2">
                        <div>
                            <h4>Claimant</h4>
                            <strong><?= htmlspecialchars($c['first_name'] . ' ' . $c['last_name']) ?></strong><br>
                            <a href="mailto:<?= htmlspecialchars($c['email']) ?>"><?= htmlspecialchars($c['email']) ?></a><br>
                            <?= htmlspecialchars($c['phone'] ?? '') ?>
                        </div>
                        <div>
                            <h4>Proof provided</h4>
                            <p style="font-size:.9rem;white-space:pre-wrap;"><?= htmlspecialchars($c['proof'] ?? '') ?></p>
                        </div>
                    </div>

                    <?php if ($c['listing_member_id']): ?>
                        <div class="alert alert-info mt-2">
                            <strong>Heads up:</strong> This listing is already assigned to member #<?= $c['listing_member_id'] ?>.
                            Approving will reassign it to whoever owns the claim email.
                        </div>
                    <?php endif; ?>

                    <?php if ($c['status'] === 'pending'): ?>
                        <div style="display:flex;gap:1rem;margin-top:1rem;">
                            <form method="post" action="claims.php" style="display:inline;"
                                  onsubmit="return confirm('Approve this claim?');">
                                <?= csrf_field() ?>
                                <input type="hidden" name="claim_id" value="<?= $c['id'] ?>">
                                <input type="hidden" name="do" value="approve">
                                <button type="submit" class="btn">Approve</button>
                            </form>
                            <form method="post" action="claims.php" style="display:inline;flex:1;"
                                  onsubmit="return confirm('Reject this claim?');">
                                <?= csrf_field() ?>
                                <input type="hidden" name="claim_id" value="<?= $c['id'] ?>">
                                <input type="hidden" name="do" value="reject">
                                <input type="text" name="reason" placeholder="Reason for rejection (emailed to claimant)"
                                       style="width:calc(100% - 140px);margin-right:.5rem;">
                                <button type="submit" class="btn" style="background:#fde0e0;border-color:#9b1c1c;color:#9b1c1c;">Reject</button>
                            </form>
                        </div>
                    <?php else: ?>
                        <p class="muted mt-2" style="font-size:.85rem;">
                            <?= $c['status'] ?> <?= $c['reviewed_at'] ? 'on ' . date('j M Y', strtotime($c['reviewed_at'])) : '' ?>
                        </p>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</section>

<?php require __DIR__ . '/_footer.php'; ?>