<?php
require_once 'includes/init.php';

// Redirect if already logged in
if (isAuthenticated()) {
    redirect(APP_URL . '/chats.php');
}

$pageTitle = 'Sign Up';
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'signup') {
        $name = sanitizeInput($_POST['name'] ?? '');
        $email = sanitizeInput($_POST['email'] ?? '');
        $mobile = sanitizeInput($_POST['mobile'] ?? '');
        $uniqueId = sanitizeInput($_POST['unique_id'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        // Validation
        if (empty($name) || empty($email) || empty($mobile) || empty($uniqueId) || empty($password)) {
            $error = 'Please fill in all required fields.';
        } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $error = 'Please enter a valid email address.';
        } else if (strlen($password) < 6) {
            $error = 'Password must be at least 6 characters long.';
        } else if ($password !== $confirmPassword) {
            $error = 'Passwords do not match.';
        } else if (strlen($uniqueId) < 4) {
            $error = 'Unique ID must be at least 4 characters long.';
        } else if (!preg_match('/^[a-zA-Z0-9_]+$/', $uniqueId)) {
            $error = 'Unique ID can only contain letters, numbers, and underscores.';
        } else {
            $db = getDB();
            
            // Check if email exists
            $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $error = 'Email address is already registered.';
            } else {
                // Check if unique ID exists
                $stmt = $db->prepare("SELECT id FROM users WHERE unique_id = ?");
                $stmt->execute([$uniqueId]);
                if ($stmt->fetch()) {
                    $error = 'This Unique ID is already taken. Please choose another.';
                } else {
                    // Handle profile photo upload
                    $profilePhoto = null;
                    if (isset($_FILES['profile_photo']) && $_FILES['profile_photo']['error'] === UPLOAD_ERR_OK) {
                        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
                        $fileType = $_FILES['profile_photo']['type'];
                        $fileSize = $_FILES['profile_photo']['size'];
                        
                        if (!in_array($fileType, $allowedTypes)) {
                            $error = 'Invalid file type. Only JPG, PNG, and WEBP are allowed.';
                        } else if ($fileSize > 5 * 1024 * 1024) {
                            $error = 'Profile photo must be less than 5MB.';
                        } else {
                            $ext = pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION);
                            $profilePhoto = $uniqueId . '_' . time() . '.' . $ext;
                            $uploadPath = UPLOAD_PATH . 'images/' . $profilePhoto;
                            
                            if (!move_uploaded_file($_FILES['profile_photo']['tmp_name'], $uploadPath)) {
                                $error = 'Failed to upload profile photo.';
                            }
                        }
                    }
                    
                    if (empty($error)) {
                        // Hash password
                        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
                        
                        // Insert user with pending status
                        $stmt = $db->prepare("INSERT INTO users (unique_id, name, email, mobile, password_hash, profile_photo, status) VALUES (?, ?, ?, ?, ?, ?, 'pending')");
                        $stmt->execute([$uniqueId, $name, $email, $mobile, $passwordHash, $profilePhoto]);
                        
                        $userId = $db->lastInsertId();
                        
                        // Log activity
                        $stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, details, ip_address, user_agent) VALUES (?, 'signup', 'New user registration pending approval', ?, ?)");
                        $stmt->execute([$userId, $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT'] ?? '']);
                        
                        $success = 'Account created successfully! Your account is pending admin approval. You will be notified once approved.';
                    }
                }
            }
        }
    }
}

include 'includes/header.php';
?>

<div class="relative flex min-h-screen w-full flex-col overflow-x-hidden bg-background-light dark:bg-background-dark">
    <!-- Top App Bar -->
    <div class="flex items-center bg-background-light dark:bg-background-dark p-4 pb-2 justify-between sticky top-0 z-10">
        <div class="text-slate-900 dark:text-slate-100 flex size-12 shrink-0 items-center cursor-pointer" onclick="history.back()">
            <span class="material-symbols-outlined" style="font-size: 24px;">arrow_back</span>
        </div>
        <h2 class="text-slate-900 dark:text-slate-100 text-lg font-bold leading-tight tracking-[-0.015em] flex-1 text-center pr-12"><?php echo APP_NAME; ?></h2>
    </div>

    <!-- Tab Navigation -->
    <div class="pb-3">
        <div class="flex border-b border-slate-200 dark:border-slate-800 px-4 justify-between">
            <a class="flex flex-col items-center justify-center border-b-[3px] border-primary text-primary pb-[13px] pt-4 flex-1" href="signup.php">
                <p class="text-sm font-bold leading-normal tracking-[0.015em]">Sign Up</p>
            </a>
            <a class="flex flex-col items-center justify-center border-b-[3px] border-transparent text-slate-500 dark:text-slate-400 pb-[13px] pt-4 flex-1" href="login.php">
                <p class="text-sm font-bold leading-normal tracking-[0.015em]">Log In</p>
            </a>
        </div>
    </div>

    <!-- Scrollable Content Area -->
    <div class="flex flex-col px-4 pt-5 pb-10 max-w-[480px] mx-auto w-full flex-1">
        <h2 class="text-slate-900 dark:text-slate-100 tracking-light text-[28px] font-bold leading-tight text-center pb-6">Create Account</h2>

        <?php if ($error): ?>
        <div class="bg-red-500/10 border border-red-500/20 text-red-500 px-4 py-3 rounded-xl mb-4 text-sm">
            <?php echo $error; ?>
        </div>
        <?php endif; ?>

        <?php if ($success): ?>
        <div class="bg-green-500/10 border border-green-500/20 text-green-500 px-4 py-3 rounded-xl mb-4 text-sm">
            <?php echo $success; ?>
        </div>
        <?php endif; ?>

        <?php if (!$success): ?>
        <form method="POST" action="" class="space-y-4" enctype="multipart/form-data">
            <input type="hidden" name="action" value="signup">
            
            <!-- Profile Photo -->
            <div class="flex flex-col items-center mb-6">
                <div class="relative">
                    <div id="photo-preview" class="size-24 rounded-full bg-slate-200 dark:bg-slate-800 flex items-center justify-center overflow-hidden border-2 border-primary/20">
                        <span class="material-symbols-outlined text-4xl text-slate-400">person</span>
                    </div>
                    <label for="profile_photo" class="absolute bottom-0 right-0 size-8 bg-primary text-white rounded-full flex items-center justify-center cursor-pointer shadow-lg">
                        <span class="material-symbols-outlined text-sm">camera_alt</span>
                    </label>
                    <input type="file" id="profile_photo" name="profile_photo" accept="image/jpeg,image/png,image/webp" class="hidden" onchange="previewPhoto(this)">
                </div>
                <p class="text-xs text-slate-500 dark:text-slate-400 mt-2">Add profile photo (optional)</p>
            </div>

            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Full Name <span class="text-red-500">*</span></p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">person</span>
                    <input name="name" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-4 text-base font-normal" placeholder="John Doe" type="text" required/>
                </div>
            </label>

            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Email Address <span class="text-red-500">*</span></p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">mail</span>
                    <input name="email" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-4 text-base font-normal" placeholder="name@example.com" type="email" required/>
                </div>
            </label>

            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Mobile Number <span class="text-red-500">*</span></p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">smartphone</span>
                    <input name="mobile" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-4 text-base font-normal" placeholder="+1 (555) 000-0000" type="tel" required/>
                </div>
            </label>

            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Unique ID <span class="text-red-500">*</span></p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">fingerprint</span>
                    <input name="unique_id" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-4 text-base font-normal" placeholder="Choose a unique ID (min 4 chars)" type="text" minlength="4" required/>
                </div>
                <p class="text-xs text-slate-500 dark:text-slate-400 mt-1 ml-1">Letters, numbers, and underscores only</p>
            </label>

            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Password <span class="text-red-500">*</span></p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">lock</span>
                    <input name="password" id="password" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-12 text-base font-normal" placeholder="••••••••" type="password" minlength="6" required/>
                    <span class="material-symbols-outlined absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 cursor-pointer" style="font-size: 20px;" onclick="togglePassword(this, 'password')">visibility_off</span>
                </div>
            </label>

            <label class="flex flex-col w-full">
                <p class="text-slate-700 dark:text-slate-300 text-sm font-medium leading-normal pb-1.5 ml-1">Confirm Password <span class="text-red-500">*</span></p>
                <div class="relative">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-slate-400" style="font-size: 20px;">lock</span>
                    <input name="confirm_password" id="confirm_password" class="form-input flex w-full rounded-xl text-slate-900 dark:text-slate-100 focus:outline-0 focus:ring-2 focus:ring-primary/50 border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900/50 h-14 placeholder:text-slate-400 pl-11 pr-12 text-base font-normal" placeholder="••••••••" type="password" minlength="6" required/>
                    <span class="material-symbols-outlined absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 cursor-pointer" style="font-size: 20px;" onclick="togglePassword(this, 'confirm_password')">visibility_off</span>
                </div>
            </label>

            <button type="submit" class="mt-6 flex h-14 w-full items-center justify-center rounded-xl bg-primary px-4 text-base font-bold tracking-wide text-white transition-opacity active:opacity-90">
                Create Secure Account
            </button>
        </form>
        <?php endif; ?>

        <!-- Security Footer -->
        <div class="mt-auto pt-6 flex flex-col items-center justify-center gap-2">
            <div class="flex items-center gap-2 text-slate-500 dark:text-slate-400">
                <span class="material-symbols-outlined" style="font-size: 16px;">verified_user</span>
                <p class="text-xs">End-to-end encrypted security</p>
            </div>
            <p class="text-xs text-slate-500 dark:text-slate-500 text-center px-6">
                <?php if ($success): ?>
                <a href="login.php" class="text-primary hover:underline font-medium">Go to Login</a>
                <?php else: ?>
                By signing up, you agree to our <a class="text-primary hover:underline" href="#">Terms of Service</a> and <a class="text-primary hover:underline" href="#">Privacy Policy</a>.
                <?php endif; ?>
            </p>
        </div>
    </div>
</div>

<script>
    function previewPhoto(input) {
        const preview = document.getElementById('photo-preview');
        if (input.files && input.files[0]) {
            const reader = new FileReader();
            reader.onload = function(e) {
                preview.innerHTML = '<img src="' + e.target.result + '" class="w-full h-full object-cover">';
            };
            reader.readAsDataURL(input.files[0]);
        }
    }

    function togglePassword(icon, inputId) {
        const input = document.getElementById(inputId);
        if (input.type === 'password') {
            input.type = 'text';
            icon.textContent = 'visibility';
        } else {
            input.type = 'password';
            icon.textContent = 'visibility_off';
        }
    }
</script>

<?php
$hideFooter = true;
include 'includes/footer.php';
?>
