<?php
session_start();

// Security headers
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");

error_reporting(0);
require_once('includes/config.php');

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Code for User Registration
if (isset($_POST['submit'])) {
    // Verify CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['errmsg'] = "Invalid request. Please try again.";
    } else {
        // Sanitize and validate inputs
        $name = htmlspecialchars(trim($_POST['fullname']), ENT_QUOTES, 'UTF-8');
        $email = filter_var(trim($_POST['emailid']), FILTER_SANITIZE_EMAIL);
        $contactno = preg_replace('/[^0-9+]/', '', trim($_POST['contactno']));
        $password = $_POST['password'];
        $confirmPassword = $_POST['confirmpassword'];

        $errors = [];

        // Validate name
        if (strlen($name) < 2 || strlen($name) > 100) {
            $errors[] = "Name must be between 2 and 100 characters";
        }

        // Validate email
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = "Invalid email format";
        }

        // Validate contact number
        if (strlen($contactno) < 10 || strlen($contactno) > 15) {
            $errors[] = "Contact number must be between 10 and 15 digits";
        }

        // Validate password strength
        if (strlen($password) < 8) {
            $errors[] = "Password must be at least 8 characters long";
        }
        if (!preg_match('/[A-Z]/', $password)) {
            $errors[] = "Password must contain at least one uppercase letter";
        }
        if (!preg_match('/[a-z]/', $password)) {
            $errors[] = "Password must contain at least one lowercase letter";
        }
        if (!preg_match('/[0-9]/', $password)) {
            $errors[] = "Password must contain at least one number";
        }

        // Check password match
        if ($password !== $confirmPassword) {
            $errors[] = "Passwords do not match";
        }

        if (!empty($errors)) {
            $_SESSION['errmsg'] = implode("<br>", $errors);
        } else {
            // Check if email already exists
            $check_stmt = $con->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
            $check_stmt->bind_param("s", $email);
            $check_stmt->execute();
            $check_result = $check_stmt->get_result();

            if ($check_result->num_rows > 0) {
                $_SESSION['errmsg'] = "Email already registered. Please login instead.";
                $check_stmt->close();
            } else {
                $check_stmt->close();

                // Hash password using bcrypt
                $password_hash = password_hash($password, PASSWORD_DEFAULT, ['cost' => 12]);

                // Start transaction for data integrity
                mysqli_begin_transaction($con);

                try {
                    // Step 1: Insert into users table (authentication)
                    $user_stmt = $con->prepare("INSERT INTO users(email, password, role) VALUES (?, ?, 'customer')");
                    $user_stmt->bind_param("ss", $email, $password_hash);

                    if (!$user_stmt->execute()) {
                        throw new Exception("Failed to create user account");
                    }

                    // Get the inserted user ID
                    $user_id = $con->insert_id;
                    $user_stmt->close();

                    // Step 2: Insert into user_details table (profile)
                    $details_stmt = $con->prepare("INSERT INTO user_details(user_id, name, contactno) VALUES (?, ?, ?)");
                    $details_stmt->bind_param("iss", $user_id, $name, $contactno);

                    if (!$details_stmt->execute()) {
                        throw new Exception("Failed to create user profile");
                    }
                    $details_stmt->close();

                    // Commit transaction
                    mysqli_commit($con);

                    $_SESSION['successmsg'] = "Registration successful! You can now login.";

                    // Redirect to login page
                    header("location: login.php");
                    exit();

                } catch (Exception $e) {
                    // Rollback transaction on error
                    mysqli_rollback($con);
                    $_SESSION['errmsg'] = "Registration failed. Please try again later.";
                }
            }
        }
    }

    // Regenerate CSRF token after submission
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Check if already logged in
if (isset($_SESSION['login']) && !empty($_SESSION['login'])) {
    header("location: index.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Create an account at Awesome Mall - Start shopping today">
    <title>Sign Up - Awesome Mall</title>

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
        integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
        crossorigin="anonymous">

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

    <style>
        :root {
            --am-primary: #E8663D;
            --am-primary-hover: #d25532;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            overflow-x: hidden;
        }

        .auth-container {
            min-height: 100vh;
            display: flex;
        }

        .auth-brand-side {
            flex: 1;
            background: linear-gradient(135deg, var(--am-primary) 0%, var(--am-primary-hover) 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 60px;
            position: relative;
            overflow: hidden;
        }

        .auth-brand-side::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
        }

        .brand-content {
            position: relative;
            z-index: 1;
            text-align: center;
            color: #fff;
        }

        .brand-content i {
            font-size: 80px;
            margin-bottom: 30px;
            opacity: 0.9;
        }

        .brand-content h3 {
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 16px;
        }

        .brand-content p {
            font-size: 18px;
            opacity: 0.95;
            line-height: 1.6;
        }

        .features {
            margin-top: 40px;
            display: grid;
            gap: 20px;
        }

        .feature-item {
            display: flex;
            align-items: center;
            gap: 16px;
            padding: 16px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 12px;
            backdrop-filter: blur(10px);
        }

        .feature-icon {
            width: 50px;
            height: 50px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }

        .feature-text h5 {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 4px;
        }

        .feature-text p {
            font-size: 14px;
            margin: 0;
            opacity: 0.9;
        }

        .auth-form-side {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px 20px;
            background: #fff;
            overflow-y: auto;
        }

        .auth-form-wrapper {
            width: 100%;
            max-width: 500px;
        }

        .logo-section {
            text-align: center;
            margin-bottom: 40px;
        }

        .logo-section img {
            height: 45px;
            margin-bottom: 10px;
        }

        .logo-section h1 {
            font-size: 28px;
            font-weight: 700;
            color: #1a1a1a;
            margin-bottom: 8px;
        }

        .logo-section p {
            color: #666;
            font-size: 15px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            font-weight: 500;
            font-size: 14px;
            color: #333;
            margin-bottom: 8px;
            display: block;
        }

        .form-control {
            height: 48px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 12px 16px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-control:focus {
            border-color: var(--am-primary);
            box-shadow: 0 0 0 3px rgba(232, 102, 61, 0.1);
        }

        .password-toggle {
            position: relative;
        }

        .password-toggle .toggle-icon {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #999;
            font-size: 18px;
        }

        .password-strength {
            height: 4px;
            background: #e0e0e0;
            border-radius: 2px;
            margin-top: 8px;
            overflow: hidden;
        }

        .password-strength-bar {
            height: 100%;
            width: 0;
            transition: all 0.3s;
            border-radius: 2px;
        }

        .password-strength-bar.weak {
            width: 33%;
            background: #ff4444;
        }

        .password-strength-bar.medium {
            width: 66%;
            background: #ffbb33;
        }

        .password-strength-bar.strong {
            width: 100%;
            background: #00C851;
        }

        .btn-primary {
            height: 48px;
            background: var(--am-primary);
            border: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 15px;
            transition: all 0.3s;
        }

        .btn-primary:hover {
            background: var(--am-primary-hover);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(232, 102, 61, 0.3);
        }

        .divider {
            display: flex;
            align-items: center;
            margin: 30px 0;
            color: #999;
            font-size: 14px;
        }

        .divider::before,
        .divider::after {
            content: '';
            flex: 1;
            height: 1px;
            background: #e0e0e0;
        }

        .divider span {
            padding: 0 16px;
        }

        .switch-form {
            text-align: center;
            margin-top: 30px;
            color: #666;
            font-size: 14px;
        }

        .switch-form a {
            color: var(--am-primary);
            text-decoration: none;
            font-weight: 600;
        }

        .error-message {
            background: #fee;
            border-left: 4px solid #d32f2f;
            color: #d32f2f;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            line-height: 1.5;
        }

        .success-message {
            background: #e8f5e9;
            border-left: 4px solid #4caf50;
            color: #2e7d32;
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .password-requirements {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 12px;
            margin-top: 8px;
            font-size: 13px;
        }

        .password-requirements ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .password-requirements li {
            padding: 4px 0;
            color: #666;
        }

        .password-requirements li.valid {
            color: #00C851;
        }

        .password-requirements li .fa-check {
            color: #00C851;
        }

        .password-requirements li .fa-times {
            color: #d32f2f;
        }

        @media (max-width: 991px) {
            .auth-brand-side {
                display: none;
            }
        }

        @media (max-width: 576px) {
            .logo-section h1 {
                font-size: 24px;
            }
        }

        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .auth-form-wrapper {
            animation: fadeInUp 0.6s ease-out;
        }
    </style>
</head>

<body>
    <div class="auth-container">
        <div class="auth-brand-side">
            <div class="brand-content">
                <i class="fas fa-user-plus"></i>
                <h3>Join Awesome Mall</h3>
                <p>Start shopping for your favorite products today</p>

                <div class="features">
                    <div class="feature-item">
                        <div class="feature-icon">
                            <i class="fas fa-shopping-cart"></i>
                        </div>
                        <div class="feature-text text-start">
                            <h5>Exclusive Deals</h5>
                            <p>Access member-only discounts</p>
                        </div>
                    </div>

                    <div class="feature-item">
                        <div class="feature-icon">
                            <i class="fas fa-history"></i>
                        </div>
                        <div class="feature-text text-start">
                            <h5>Order Tracking</h5>
                            <p>Track all your orders easily</p>
                        </div>
                    </div>

                    <div class="feature-item">
                        <div class="feature-icon">
                            <i class="fas fa-heart"></i>
                        </div>
                        <div class="feature-text text-start">
                            <h5>Wishlist</h5>
                            <p>Save favorites for later</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="auth-form-side">
            <div class="auth-form-wrapper">
                <div class="logo-section">
                    <a href="index.php">
                        <img src="assets/images/logo.png" alt="Awesome Mall">
                    </a>
                    <h1>Create Account</h1>
                    <p>Sign up to start shopping</p>
                </div>

                <?php if (!empty($_SESSION['errmsg'])): ?>
                    <div class="error-message">
                        <i class="fas fa-exclamation-circle"></i>
                        <?php echo $_SESSION['errmsg']; ?>
                    </div>
                    <?php $_SESSION['errmsg'] = ""; ?>
                <?php endif; ?>

                <form method="post" name="register" onsubmit="return validateForm()" autocomplete="off">
                    <input type="hidden" name="csrf_token"
                        value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">

                    <div class="form-group">
                        <label class="form-label">Full Name</label>
                        <input type="text" name="fullname" class="form-control" placeholder="Enter your full name"
                            required minlength="2" maxlength="100" autocomplete="name">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Email Address</label>
                        <input type="email" name="emailid" class="form-control" placeholder="Enter your email" required
                            autocomplete="email" maxlength="255">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Contact Number</label>
                        <input type="tel" name="contactno" class="form-control" placeholder="Enter your phone number"
                            required minlength="10" maxlength="15" pattern="[0-9+]+" autocomplete="tel">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Password</label>
                        <div class="password-toggle">
                            <input type="password" name="password" class="form-control" id="signupPassword"
                                placeholder="Create a password" required minlength="8" maxlength="255"
                                onkeyup="checkPasswordStrength()" autocomplete="new-password">
                            <i class="fas fa-eye toggle-icon" onclick="togglePassword('signupPassword', this)"></i>
                        </div>
                        <div class="password-strength">
                            <div class="password-strength-bar" id="strength-bar"></div>
                        </div>
                        <div class="password-requirements" id="password-requirements">
                            <ul>
                                <li id="length-check"><i class="fas fa-times"></i> At least 8 characters</li>
                                <li id="uppercase-check"><i class="fas fa-times"></i> One uppercase letter</li>
                                <li id="lowercase-check"><i class="fas fa-times"></i> One lowercase letter</li>
                                <li id="number-check"><i class="fas fa-times"></i> One number</li>
                            </ul>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Confirm Password</label>
                        <div class="password-toggle">
                            <input type="password" name="confirmpassword" class="form-control" id="confirmPassword"
                                placeholder="Confirm your password" required autocomplete="new-password">
                            <i class="fas fa-eye toggle-icon" onclick="togglePassword('confirmPassword', this)"></i>
                        </div>
                        <small id="confirm-feedback" class="form-text"></small>
                    </div>

                    <button type="submit" name="submit" class="btn btn-primary w-100">
                        <i class="fas fa-user-plus me-2"></i> Create Account
                    </button>
                </form>

                <div class="divider">
                    <span>OR</span>
                </div>

                <div class="switch-form">
                    Already have an account? <a href="login.php">Login Now</a>
                </div>
            </div>
        </div>
    </div>

    <script>
        function togglePassword(inputId, icon) {
            const input = document.getElementById(inputId);
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }

        function checkPasswordStrength() {
            const password = document.getElementById('signupPassword').value;
            const strengthBar = document.getElementById('strength-bar');

            let strength = 0;
            const checks = {
                length: password.length >= 8,
                uppercase: /[A-Z]/.test(password),
                lowercase: /[a-z]/.test(password),
                number: /[0-9]/.test(password)
            };

            // Update requirement indicators
            updateCheck('length-check', checks.length);
            updateCheck('uppercase-check', checks.uppercase);
            updateCheck('lowercase-check', checks.lowercase);
            updateCheck('number-check', checks.number);

            // Calculate strength
            Object.values(checks).forEach(check => { if (check) strength++; });

            strengthBar.className = 'password-strength-bar';

            if (strength < 2) {
                strengthBar.classList.add('weak');
            } else if (strength < 4) {
                strengthBar.classList.add('medium');
            } else {
                strengthBar.classList.add('strong');
            }
        }

        function updateCheck(id, isValid) {
            const element = document.getElementById(id);
            const icon = element.querySelector('i');

            if (isValid) {
                element.classList.add('valid');
                icon.className = 'fas fa-check';
            } else {
                element.classList.remove('valid');
                icon.className = 'fas fa-times';
            }
        }

        function validateForm() {
            const password = document.register.password.value;
            const confirmPassword = document.register.confirmpassword.value;
            const confirmFeedback = document.getElementById('confirm-feedback');

            if (password !== confirmPassword) {
                confirmFeedback.textContent = 'Passwords do not match!';
                confirmFeedback.style.color = '#d32f2f';
                document.register.confirmpassword.focus();
                return false;
            }

            // Check password requirements
            if (password.length < 8) {
                alert('Password must be at least 8 characters long');
                return false;
            }

            if (!/[A-Z]/.test(password)) {
                alert('Password must contain at least one uppercase letter');
                return false;
            }

            if (!/[a-z]/.test(password)) {
                alert('Password must contain at least one lowercase letter');
                return false;
            }

            if (!/[0-9]/.test(password)) {
                alert('Password must contain at least one number');
                return false;
            }

            return true;
        }

        // Real-time password match feedback
        document.getElementById('confirmPassword')?.addEventListener('keyup', function () {
            const password = document.getElementById('signupPassword').value;
            const confirmPassword = this.value;
            const feedback = document.getElementById('confirm-feedback');

            if (confirmPassword.length > 0) {
                if (password === confirmPassword) {
                    feedback.textContent = 'Passwords match ✓';
                    feedback.style.color = '#00C851';
                } else {
                    feedback.textContent = 'Passwords do not match';
                    feedback.style.color = '#d32f2f';
                }
            } else {
                feedback.textContent = '';
            }
        });

        // Prevent form resubmission on page refresh
        if (window.history.replaceState) {
            window.history.replaceState(null, null, window.location.href);
        }
    </script>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
        crossorigin="anonymous"></script>
</body>

</html>
