<?php
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/mail.php';

$page_title = 'Claim your business';
$submitted = false;
$error = '';

// Build the dropdown of unclaimed listings
$unclaimed = db_all(
    'SELECT id, name, address FROM listings WHERE member_id IS NULL AND published = 1 ORDER BY name'
);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();

    $required = ['listing_id', 'first_name', 'last_name', 'email', 'proof'];
    foreach ($required as $f) {
        if (empty($_POST[$f])) {
            $error = 'Please fill in all required fields.';
            break;
        }
    }

    $email = trim($_POST['email'] ?? '');
    if (!$error && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
    }

    if (!$error) {
        db_insert('business_claims', [
            'listing_id' => (int)$_POST['listing_id'],
            'email'      => $email,
            'first_name' => trim($_POST['first_name']),
            'last_name'  => trim($_POST['last_name']),
            'phone'      => trim($_POST['phone'] ?? '') ?: null,
            'proof'      => trim($_POST['proof']),
        ]);

        // Notify admin
        mail_send(
            SITE_EMAIL,
            'New business claim request',
            "A new claim has been submitted.\n\n" .
            "Listing ID: {$_POST['listing_id']}\n" .
            "Name: {$_POST['first_name']} {$_POST['last_name']}\n" .
            "Email: $email\n\n" .
            "Proof: {$_POST['proof']}\n\n" .
            "Review in the admin panel."
        );

        $submitted = true;
    }
}

require 'includes/header.php';
?>

<section class="page-banner">
    <div class="container">
        <h1>Claim your business</h1>
        <p>Already listed in our directory? Take ownership and start managing your listing.</p>
    </div>
</section>

<section class="section">
    <div class="container" style="max-width:640px;">

        <?php if ($submitted): ?>
            <div class="alert alert-success">
                <strong>Claim submitted.</strong>
                Our team reviews claims within 1&ndash;2 business days. You'll hear from us on the email you provided.
            </div>
            <p class="text-center mt-3"><a href="login.php">&larr; Back to login</a></p>

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

            <?php if (empty($unclaimed)): ?>
                <div class="alert alert-info">
                    <strong>No unclaimed listings right now.</strong>
                    If you don't see your business in the directory, the quickest path is to
                    <a href="become-member.php">sign up as a new member</a> — our team can then merge records if needed.
                </div>
            <?php else: ?>
                <div class="card">
                    <form method="post" action="claim-business.php">
                        <?= csrf_field() ?>

                        <label for="listing_id">Your business *</label>
                        <select id="listing_id" name="listing_id" required>
                            <option value="">&mdash; choose &mdash;</option>
                            <?php foreach ($unclaimed as $l): ?>
                                <option value="<?= $l['id'] ?>">
                                    <?= htmlspecialchars($l['name']) ?>
                                    <?= $l['address'] ? ' — ' . htmlspecialchars($l['address']) : '' ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <div class="grid grid-2" style="gap:0 1.25rem;">
                            <div>
                                <label for="first_name">First name *</label>
                                <input type="text" id="first_name" name="first_name" required>
                            </div>
                            <div>
                                <label for="last_name">Last name *</label>
                                <input type="text" id="last_name" name="last_name" required>
                            </div>
                        </div>

                        <label for="email">Your email *</label>
                        <input type="email" id="email" name="email" required>

                        <label for="phone">Phone</label>
                        <input type="tel" id="phone" name="phone">

                        <label for="proof">Proof of ownership *
                            <small>(domain of your business email, VAT number, website URL — anything we can verify)</small>
                        </label>
                        <textarea id="proof" name="proof" required placeholder="e.g. I'm the owner. Business email: me@mybusiness.co.za, VAT: 4123456789, website: https://…"></textarea>

                        <button type="submit" class="btn btn-block mt-3">Submit claim</button>
                    </form>
                </div>
            <?php endif; ?>

            <p class="text-center mt-3" style="font-size:.9rem;">
                <a href="login.php">&larr; Back to login</a>
            </p>
        <?php endif; ?>
    </div>
</section>

<?php require 'includes/footer.php'; ?>
