<?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/cart.php';

if (is_customer_logged_in()) {
    redirect(BASE_URL . '/public/account.php');
}

$pageTitle = 'Create Account | LOVE-U Essentials';
$pageDescription = 'Create your LOVE-U Essentials customer account.';

$error = '';
$success = '';

$prefilledReferralCode = trim($_GET['ref'] ?? '');

if (is_post()) {
    if (!verify_csrf()) {
        $error = 'Invalid request. Please refresh and try again.';
    } else {
        $firstName = trim($_POST['first_name'] ?? '');
        $lastName = trim($_POST['last_name'] ?? '');
        $email = strtolower(trim($_POST['email'] ?? ''));
        $phone = trim($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        $enteredReferralCode = strtoupper(trim($_POST['referral_code'] ?? ''));

        if ($firstName === '') {
            $error = 'First name is required.';
        } elseif ($lastName === '') {
            $error = 'Last name is required.';
        } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } elseif (strlen($password) < 8) {
            $error = 'Password must be at least 8 characters.';
        } elseif ($password !== $confirmPassword) {
            $error = 'Passwords do not match.';
        } else {
            try {
                $pdo->beginTransaction();

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

                if ($existingCustomer) {
                    throw new Exception('An account already exists with this email address.');
                }

                $referrerCustomer = null;

                if ($enteredReferralCode !== '') {
                    $stmt = $pdo->prepare("
                        SELECT id, referral_code
                        FROM customers
                        WHERE referral_code = ?
                          AND status = 'active'
                        LIMIT 1
                    ");
                    $stmt->execute([$enteredReferralCode]);
                    $referrerCustomer = $stmt->fetch();

                    if (!$referrerCustomer) {
                        throw new Exception('Invalid referral code.');
                    }
                }

                do {
                    $newReferralCode = generate_referral_code($firstName);

                    $stmt = $pdo->prepare("
                        SELECT id
                        FROM customers
                        WHERE referral_code = ?
                        LIMIT 1
                    ");
                    $stmt->execute([$newReferralCode]);
                    $codeExists = $stmt->fetch();
                } while ($codeExists);

                $passwordHash = password_hash($password, PASSWORD_DEFAULT);

                $stmt = $pdo->prepare("
                    INSERT INTO customers (
                        first_name,
                        last_name,
                        email,
                        phone,
                        password_hash,
                        referral_code,
                        status
                    ) VALUES (?, ?, ?, ?, ?, ?, 'active')
                ");

                $stmt->execute([
                    $firstName,
                    $lastName,
                    $email,
                    $phone !== '' ? $phone : null,
                    $passwordHash,
                    $newReferralCode
                ]);

                $newCustomerId = (int) $pdo->lastInsertId();

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

                if ($referrerCustomer) {
                    $stmt = $pdo->prepare("
                        INSERT INTO referrals (
                            referrer_customer_id,
                            referred_customer_id,
                            referral_code,
                            reward_status
                        ) VALUES (?, ?, ?, 'pending')
                    ");

                    $stmt->execute([
                        $referrerCustomer['id'],
                        $newCustomerId,
                        $enteredReferralCode
                    ]);

                    $referralId = (int) $pdo->lastInsertId();

                    $stmt = $pdo->prepare("
                        INSERT INTO referral_rewards (
                            referral_id,
                            reward_type,
                            reward_value,
                            status
                        ) VALUES (?, 'points', 100, 'pending')
                    ");

                    $stmt->execute([$referralId]);
                }

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

                login_customer($newCustomer);

                $pdo->commit();

                redirect(BASE_URL . '/public/account.php?registered=1');
            } catch (Exception $e) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }

                $error = $e->getMessage();
            }
        }
    }
}

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

<section class="lue-auth-page">
    <div class="lue-auth-orb lue-auth-orb-one"></div>
    <div class="lue-auth-orb lue-auth-orb-two"></div>

    <div class="container lue-auth-grid">
        <div class="lue-auth-visual reveal-up">
            <div class="lue-auth-image">
                <img src="<?= e(BASE_URL); ?>/uploads/products/body-butter-resilience-wood.jpg" alt="LOVE-U Essentials natural body care">
            </div>

            <div class="lue-auth-floating-card">
                <span>Join LOVE-U</span>
                <strong>Earn loyalty points and save your favourites.</strong>
            </div>
        </div>

        <div class="lue-auth-card lue-auth-card-wide reveal-up reveal-delay-1">
            <div class="lue-auth-head">
                <div class="eyebrow">Create Account</div>
                <h1>Join LOVE-U</h1>
                <p>Create your account to manage orders, wishlist, loyalty points, and referral rewards.</p>
            </div>

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

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

            <form method="POST" class="lue-auth-form">
                <?= csrf_field(); ?>

                <div class="lue-auth-form-grid">
                    <div class="lue-auth-field">
                        <label>First Name *</label>
                        <input type="text" name="first_name" value="<?= e($_POST['first_name'] ?? ''); ?>" placeholder="First name" required>
                    </div>

                    <div class="lue-auth-field">
                        <label>Last Name *</label>
                        <input type="text" name="last_name" value="<?= e($_POST['last_name'] ?? ''); ?>" placeholder="Last name" required>
                    </div>
                </div>

                <div class="lue-auth-form-grid">
                    <div class="lue-auth-field">
                        <label>Email Address *</label>
                        <input type="email" name="email" value="<?= e($_POST['email'] ?? ''); ?>" placeholder="you@example.com" required>
                    </div>

                    <div class="lue-auth-field">
                        <label>Phone</label>
                        <input type="text" name="phone" value="<?= e($_POST['phone'] ?? ''); ?>" placeholder="Optional">
                    </div>
                </div>

                <div class="lue-auth-form-grid">
                    <div class="lue-auth-field">
                        <label>Password *</label>

                        <div class="lue-password-wrap">
                            <input
                                type="password"
                                name="password"
                                id="registerPassword"
                                placeholder="Minimum 8 characters"
                                required
                            >

                            <button
                                type="button"
                                class="lue-password-toggle"
                                data-target="registerPassword"
                                aria-label="Show password"
                            >
                                <svg viewBox="0 0 24 24" aria-hidden="true">
                                    <path d="M2.5 12s3.5-6.5 9.5-6.5S21.5 12 21.5 12s-3.5 6.5-9.5 6.5S2.5 12 2.5 12Z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                            </button>
                        </div>
                    </div>

                    <div class="lue-auth-field">
                        <label>Confirm Password *</label>

                        <div class="lue-password-wrap">
                            <input
                                type="password"
                                name="confirm_password"
                                id="registerConfirmPassword"
                                placeholder="Re-enter password"
                                required
                            >

                            <button
                                type="button"
                                class="lue-password-toggle"
                                data-target="registerConfirmPassword"
                                aria-label="Show password"
                            >
                                <svg viewBox="0 0 24 24" aria-hidden="true">
                                    <path d="M2.5 12s3.5-6.5 9.5-6.5S21.5 12 21.5 12s-3.5 6.5-9.5 6.5S2.5 12 2.5 12Z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>

                <div class="lue-auth-field">
                    <label>Referral Code</label>
                    <input
                        type="text"
                        name="referral_code"
                        value="<?= e($_POST['referral_code'] ?? $prefilledReferralCode); ?>"
                        placeholder="Optional referral code"
                    >
                    <small>Enter a referral code if someone invited you.</small>
                </div>

                <button type="submit" class="btn lue-auth-submit">Create Account</button>
            </form>

            <div class="lue-auth-switch">
                <span>Already have an account?</span>
                <a href="<?= e(BASE_URL); ?>/public/login.php">Login here</a>
            </div>
        </div>
    </div>
</section>

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