<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/config/db.php';

// If already logged in, redirect
if (isset($_SESSION['customer_id'])) {
    header("Location: index.php");
    exit;
}

$error = '';
$success = '';
$redirect = isset($_GET['redirect']) ? htmlspecialchars($_GET['redirect']) : 'index.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = trim($_POST['full_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $address = trim($_POST['address'] ?? '');
    
    if (empty($full_name) || empty($email) || empty($password)) {
        $error = 'All fields marked with an asterisk (*) are required.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
    } elseif (strlen($password) < 6) {
        $error = 'Password must be at least 6 characters long.';
    } else {
        try {
            // Check if email already exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $error = 'An account with this email address already exists. Please login instead.';
            } else {
                // Securely hash password and insert
                $password_hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt_insert = $pdo->prepare("INSERT INTO users (full_name, email, password, address, is_admin) VALUES (?, ?, ?, ?, ?)");
                $stmt_insert->execute([$full_name, $email, $password_hash, $address, 0]);
                
                $new_user_id = $pdo->lastInsertId();
                
                // Auto-login after successful registration
                $_SESSION['customer_id'] = $new_user_id;
                $_SESSION['customer_name'] = $full_name;
                $_SESSION['customer_email'] = $email;
                
                // Sync session wishlist to DB wishlist if any exists
                if (isset($_SESSION['wishlist']) && is_array($_SESSION['wishlist'])) {
                    $stmt_sync = $pdo->prepare("INSERT IGNORE INTO wishlist (user_id, product_id) VALUES (?, ?)");
                    foreach ($_SESSION['wishlist'] as $prod_id) {
                        $stmt_sync->execute([$new_user_id, $prod_id]);
                    }
                    unset($_SESSION['wishlist']); // Clear session wishlist after sync
                }

                header("Location: " . $redirect);
                exit;
            }
        } catch (Exception $e) {
            $error = 'Registration failed: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MARTLUX | Join the Atelier</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&family=Playfair+Display:ital,wght@0,400;0,600;0,700;1,400&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-black: #000000;
            --bg-dark: #0E0E0E;
            --bg-card: rgba(21, 21, 21, 0.75);
            --border-gray: #2A2A2A;
            --accent-gold: #DCC7A3;
            --text-white: #FFFFFF;
            --text-gray: #A0A0A0;
            --font-heading: 'Playfair Display', serif;
            --font-body: 'Montserrat', sans-serif;
        }

        body {
            background-color: var(--bg-black);
            color: var(--text-white);
            font-family: var(--font-body);
            margin: 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background-image: radial-gradient(circle at 10% 20%, rgba(220, 199, 163, 0.05) 0%, transparent 40%),
                              radial-gradient(circle at 90% 80%, rgba(220, 199, 163, 0.05) 0%, transparent 40%);
        }

        .login-container {
            width: 100%;
            max-width: 520px;
            padding: 15px;
        }

        .login-card {
            background: var(--bg-card);
            border: 1px solid var(--border-gray);
            border-radius: 20px;
            padding: 3rem 2.5rem;
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.6);
            transition: all 0.3s ease;
        }

        .brand-logo-monogram {
            height: 38px;
            width: 98px;
            object-fit: cover;
            object-position: top;
            border-radius: 4px;
        }

        .form-label {
            font-size: 0.68rem;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            font-weight: 700;
            color: var(--text-gray);
            margin-bottom: 0.5rem;
        }

        .form-control {
            background-color: rgba(14, 14, 14, 0.8) !important;
            border: 1px solid var(--border-gray) !important;
            color: var(--text-white) !important;
            border-radius: 8px;
            padding: 0.75rem 1rem;
            font-size: 0.85rem;
            transition: all 0.3s;
        }

        .form-control:focus {
            border-color: var(--accent-gold) !important;
            box-shadow: 0 0 15px rgba(220, 199, 163, 0.2) !important;
        }

        .btn-luxury {
            background-color: var(--accent-gold);
            border-color: var(--accent-gold);
            color: #000 !important;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 2px;
            font-size: 0.75rem;
            border-radius: 50px;
            padding: 0.85rem 2rem;
            width: 100%;
            transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
        }

        .btn-luxury:hover {
            background-color: var(--text-white);
            border-color: var(--text-white);
            transform: translateY(-2px);
        }

        .text-warning {
            color: var(--accent-gold) !important;
        }

        .text-muted {
            color: var(--text-gray) !important;
        }
        
        .hover-gold:hover {
            color: var(--accent-gold) !important;
        }
    </style>
</head>
<body>

<div class="login-container">
    <div class="text-center mb-4">
        <a href="index.php">
            <img src="assets/images/logo.png" alt="MARTLUX Logo" class="brand-logo-monogram">
        </a>
    </div>

    <div class="login-card">
        <h3 class="text-center mb-2" style="font-family: var(--font-heading); font-weight: 600; letter-spacing: 1px;">Join The Atelier</h3>
        <p class="text-muted text-center small mb-4">Create your private profile to unlock collection showcases & wishlists</p>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger border-danger bg-dark text-danger rounded-3 py-2 px-3 small mb-4" role="alert">
                <i class="fa-solid fa-circle-exclamation me-2"></i> <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <form action="register.php?redirect=<?php echo urlencode($redirect); ?>" method="POST">
            <!-- Full Name -->
            <div class="mb-3">
                <label for="full_name" class="form-label">Full Name *</label>
                <input type="text" class="form-control" id="full_name" name="full_name" placeholder="E.g. Elena Rostova" required>
            </div>

            <!-- Email Address -->
            <div class="mb-3">
                <label for="email" class="form-label">Email Address *</label>
                <input type="email" class="form-control" id="email" name="email" placeholder="E.g. elena@mn-direct.com" required>
            </div>

            <!-- Password -->
            <div class="mb-3">
                <label for="password" class="form-label">Password *</label>
                <input type="password" class="form-control" id="password" name="password" placeholder="At least 6 characters" required>
            </div>

            <!-- Shipping Address -->
            <div class="mb-4">
                <label for="address" class="form-label">Delivery Address</label>
                <textarea class="form-control" id="address" name="address" rows="2" placeholder="Optional - E.g. No. 12, Ward Place, Colombo"></textarea>
            </div>

            <!-- Submit -->
            <button type="submit" class="btn-luxury mb-3">Register & Explore</button>

            <!-- Sign in Link -->
            <div class="text-center mt-3 small">
                <span class="text-muted">Already a member?</span> 
                <a href="login.php?redirect=<?php echo urlencode($redirect); ?>" class="text-warning text-decoration-none hover-gold ms-1 fw-bold">Sign In Here</a>
            </div>
        </form>
    </div>

    <!-- Small Footer -->
    <div class="text-center mt-4">
        <a href="index.php" class="text-muted text-decoration-none small hover-gold">
            <i class="fa-solid fa-arrow-left me-1"></i> Return to Atelier Homepage
        </a>
    </div>
</div>

</body>
</html>
