<?php
session_start();

if (isset($_SESSION['admin']) && $_SESSION['admin'] === true) {
    header('Location: api-key-manager.php');
    exit;
}

$host = 'localhost:3306';
$dbname = 'gqdcvggs_traffic';
$username = 'gqdcvggs';
$password = 'imaors_management.346980*#@-onlyforcpanel;forchange';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $terms_accepted = isset($_POST['terms_accepted']);
    $age_verified = isset($_POST['age_verified']);
    
    if (empty($username) || empty($email) || empty($password) || empty($confirm_password)) {
        $error = 'All fields are required';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Invalid email format';
    } elseif ($password !== $confirm_password) {
        $error = 'Passwords do not match';
    } elseif (strlen($password) < 8) {
        $error = 'Password must be at least 8 characters';
    } elseif (!$terms_accepted) {
        $error = 'You must accept the Terms of Service';
    } elseif (!$age_verified) {
        $error = 'You must confirm you are 18 years or older';
    } else {
        try {
            // Check if username already exists
            $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->rowCount() > 0) {
                $error = 'Username already exists';
            } else {
                // Check if email already exists
                $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE email = ?");
                $stmt->execute([$email]);
                if ($stmt->rowCount() > 0) {
                    $error = 'Email already exists';
                } else {
                    // Create new user
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("INSERT INTO admin_users (username, email, password, terms_accepted, created_at) VALUES (?, ?, ?, 1, NOW())");
                    $stmt->execute([$username, $email, $hashed_password]);
                    
                    $success = 'Account created successfully. You can now log in.';
                }
            }
        } catch (PDOException $e) {
            $error = 'Registration error: ' . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Account - TrafficLight</title>
    <link rel="icon" type="image/png" href="traffic_logo.png">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        'sans': ['Inter', 'sans-serif']
                    },
                    colors: {
                        primary: {
                            50: '#f0f9ff',
                            100: '#e0f2fe',
                            200: '#bae6fd',
                            300: '#7dd3fc',
                            400: '#38bdf8',
                            500: '#0ea5e9',
                            600: '#0284c7',
                            700: '#0369a1',
                            800: '#075985',
                            900: '#0c4a6e'
                        }
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-gray-50 min-h-screen py-12 px-4 sm:px-6 lg:px-8 flex flex-col items-center justify-center">
    <div class="max-w-md w-full space-y-8 p-6 bg-white rounded-xl shadow-md">
        <div class="text-center">
            <img src="traffic_logo.png" alt="Logo" class="mx-auto h-12 w-auto">
            <h2 class="mt-4 text-2xl font-bold text-gray-900">Create an Account</h2>
            <p class="mt-2 text-sm text-gray-600">Join TrafficLightAPI and manage API keys</p>
        </div>
        
        <?php if (!empty($error)): ?>
            <div class="rounded-md bg-red-50 p-4">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-circle text-red-400"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-red-800"><?php echo $error; ?></p>
                    </div>
                </div>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($success)): ?>
            <div class="rounded-md bg-green-50 p-4">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-check-circle text-green-400"></i>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm font-medium text-green-800"><?php echo $success; ?></p>
                        <div class="mt-2">
                            <a href="admin-login.php" class="text-sm font-medium text-primary-600 hover:text-primary-500">
                                Go to Login <i class="fas fa-arrow-right ml-1"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <form class="mt-8 space-y-6" method="POST">
                <div class="rounded-md shadow-sm space-y-4">
                    <div>
                        <label for="username" class="block text-sm font-medium text-gray-700 mb-1">Username</label>
                        <input id="username" name="username" type="text" required class="appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm" placeholder="Choose a username">
                    </div>
                    
                    <div>
                        <label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                        <input id="email" name="email" type="email" required class="appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm" placeholder="Your email address">
                    </div>
                    
                    <div>
                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">Password</label>
                        <input id="password" name="password" type="password" required class="appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm" placeholder="Create a password">
                        <p class="mt-1 text-xs text-gray-500">Must be at least 8 characters</p>
                    </div>
                    
                    <div>
                        <label for="confirm_password" class="block text-sm font-medium text-gray-700 mb-1">Confirm Password</label>
                        <input id="confirm_password" name="confirm_password" type="password" required class="appearance-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm" placeholder="Confirm your password">
                    </div>
                </div>

                <div class="space-y-3">
                    <div class="flex items-start">
                        <div class="flex items-center h-5">
                            <input id="terms_accepted" name="terms_accepted" type="checkbox" class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded">
                        </div>
                        <div class="ml-3 text-sm">
                            <label for="terms_accepted" class="font-medium text-gray-700">I accept the <a href="#" class="text-primary-600 hover:text-primary-500" id="showTermsBtn">Terms of Service</a> of Imators</label>
                        </div>
                    </div>
                    
                    <div class="flex items-start">
                        <div class="flex items-center h-5">
                            <input id="age_verified" name="age_verified" type="checkbox" class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded">
                        </div>
                        <div class="ml-3 text-sm">
                            <label for="age_verified" class="font-medium text-gray-700">I confirm that I am 18 years or older</label>
                        </div>
                    </div>
                </div>

                <div>
                    <button type="submit" class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-primary-600 hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                        <span class="absolute left-0 inset-y-0 flex items-center pl-3">
                            <i class="fas fa-user-plus text-primary-500 group-hover:text-primary-400"></i>
                        </span>
                        Create Account
                    </button>
                </div>
                
                <div class="text-center text-sm">
                    <p>Already have an account? 
                        <a href="./login" class="font-medium text-primary-600 hover:text-primary-500">
                            Sign in
                        </a>
                    </p>
                </div>
            </form>
        <?php endif; ?>
    </div>
    
    <!-- Terms of Service Modal -->
    <div id="termsModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg max-w-2xl w-full max-h-screen overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-900">TrafficLight API Terms of Service</h3>
                <button id="closeTermsBtn" type="button" class="text-gray-400 hover:text-gray-500">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="px-6 py-4 overflow-y-auto max-h-[60vh]">
                <h4 class="text-base font-semibold mb-2">1. Acceptance of Terms</h4>
                <p class="text-sm text-gray-600 mb-4">
                    By accessing or using the TrafficLight service ("Service") provided by Imators ("Company", "we", "us", "our"), you agree to be bound by these Terms of Service ("Terms") and those presented and linked to our services, <a class="underline" href="https://imators.com/terms-of-use">available here</a>. If you do not agree to these Terms, do not use our Service.
                </p>
                
                <h4 class="text-base font-semibold mb-2">2. Description of Service</h4>
                <p class="text-sm text-gray-600 mb-4">
                    TrafficLight provides real-time traffic light data and API access to that data. The Service may include updates, enhancements, new features, and/or the release of new versions.
                </p>
                
                <h4 class="text-base font-semibold mb-2">3. User Accounts</h4>
                <p class="text-sm text-gray-600 mb-4">
                    To access certain features of the Service, you must create an account. You agree to provide accurate information and keep your account information updated. You are responsible for maintaining the confidentiality of your account credentials and for all activities that occur under your account.
                </p>
                
                <h4 class="text-base font-semibold mb-2">4. API Usage and Rate Limits</h4>
                <p class="text-sm text-gray-600 mb-4">
                    Our API is subject to rate limits as specified in the documentation. We reserve the right to modify these limits at any time. Any attempt to circumvent these limits may result in the suspension or termination of your account.
                </p>
                
                <h4 class="text-base font-semibold mb-2">5. Data Ownership and Privacy</h4>
                <p class="text-sm text-gray-600 mb-4">
                    The Company owns all right, title, and interest to the data provided through the Service. By using our Service, you agree to our Privacy Policy, which describes how we collect, use, and share information.
                </p>
                
                <h4 class="text-base font-semibold mb-2">6. Acceptable Use</h4>
                <p class="text-sm text-gray-600 mb-4">
                    You agree not to use the Service to:
                    <br>• Violate any laws or regulations
                    <br>• Infringe the rights of others
                    <br>• Interfere with the operation of the Service
                    <br>• Distribute malware or malicious code
                    <br>• Conduct unauthorized penetration testing or security assessments
                </p>
                
                <h4 class="text-base font-semibold mb-2">7. Termination</h4>
                <p class="text-sm text-gray-600 mb-4">
                    We reserve the right to suspend or terminate your access to the Service at any time for any reason without notice. You may terminate your account at any time by contacting us.
                </p>
                
                <h4 class="text-base font-semibold mb-2">8. Disclaimer of Warranties</h4>
                <p class="text-sm text-gray-600 mb-4">
                    THE SERVICE IS PROVIDED "AS IS" WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. WE DISCLAIM ALL WARRANTIES, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
                </p>
                
                <h4 class="text-base font-semibold mb-2">9. Limitation of Liability</h4>
                <p class="text-sm text-gray-600 mb-4">
                    IN NO EVENT SHALL THE COMPANY BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES ARISING OUT OF OR RELATED TO YOUR USE OF THE SERVICE.
                </p>
                
                <h4 class="text-base font-semibold mb-2">10. Changes to Terms</h4>
                <p class="text-sm text-gray-600 mb-4">
                    We reserve the right to modify these Terms at any time. Continued use of the Service after any such changes constitutes your acceptance of the new Terms.
                </p>
                
                <h4 class="text-base font-semibold mb-2">11. Contact Information</h4>
                <p class="text-sm text-gray-600 mb-4">
                    If you have any questions about these Terms, please contact us at support@imators.com.
                </p>
                
                <p class="text-sm text-gray-600 font-medium mt-6">
                    Last updated: April 6, 2025
                </p>
            </div>
            <div class="px-6 py-4 border-t border-gray-200 flex justify-end">
                <button id="acceptTermsBtn" type="button" class="px-4 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 text-sm font-medium">
                    I Accept
                </button>
            </div>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const termsModal = document.getElementById('termsModal');
            const showTermsBtn = document.getElementById('showTermsBtn');
            const closeTermsBtn = document.getElementById('closeTermsBtn');
            const acceptTermsBtn = document.getElementById('acceptTermsBtn');
            const termsCheckbox = document.getElementById('terms_accepted');
            
            showTermsBtn.addEventListener('click', function(e) {
                e.preventDefault();
                termsModal.classList.remove('hidden');
            });
            
            closeTermsBtn.addEventListener('click', function() {
                termsModal.classList.add('hidden');
            });
            
            acceptTermsBtn.addEventListener('click', function() {
                termsCheckbox.checked = true;
                termsModal.classList.add('hidden');
            });
            
            // Close modal if clicked outside content
            termsModal.addEventListener('click', function(e) {
                if (e.target === termsModal) {
                    termsModal.classList.add('hidden');
                }
            });
        });
    </script>
</body>
</html>