<?php
// Ensure no output before session_start
if (ob_get_level()) { ob_end_clean(); }
ob_start();
session_start();
require_once 'config.php';

// Protect store registration - require secret key
$required_key = $config['store_registration_key'] ?? 'd-bundles-2024-secret-key';
$provided_key = $_GET['key'] ?? '';

if (empty($provided_key) || $provided_key !== $required_key) {
    // Redirect to homepage with error message
    header('Location: index.php?error=access_denied');
    exit();
}

$error_message = '';
$success_message = '';

function columnExists(mysqli $conn, string $table, string $column): bool {
    $stmt = $conn->prepare("SHOW COLUMNS FROM `$table` LIKE ?");
    $stmt->bind_param("s", $column);
    $stmt->execute();
    $result = $stmt->get_result();
    $exists = $result && $result->num_rows > 0;
    $stmt->close();
    return $exists;
}

// Ensure required columns exist
try {
    if (!columnExists($conn, 'agents', 'email')) {
        mysqli_query($conn, "ALTER TABLE agents ADD COLUMN email VARCHAR(191) NULL UNIQUE AFTER username");
    }
    if (!columnExists($conn, 'agents', 'password_hash')) {
        mysqli_query($conn, "ALTER TABLE agents ADD COLUMN password_hash VARCHAR(255) NULL AFTER email");
    }
    if (!columnExists($conn, 'agents', 'phone')) {
        mysqli_query($conn, "ALTER TABLE agents ADD COLUMN phone VARCHAR(20) NULL AFTER email");
    }
} catch (Throwable $e) {}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $password = isset($_POST['password']) ? (string)$_POST['password'] : '';
    $confirm_password = isset($_POST['confirm_password']) ? (string)$_POST['confirm_password'] : '';

    // Validation
    if (empty($username) || empty($email) || empty($phone) || empty($password) || empty($confirm_password)) {
        $error_message = "All fields are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_message = "Please enter a valid email address.";
    } elseif (strlen($username) < 3) {
        $error_message = "Username must be at least 3 characters long.";
    } elseif (strlen($password) < 6) {
        $error_message = "Password must be at least 6 characters long.";
    } elseif ($password !== $confirm_password) {
        $error_message = "Passwords do not match.";
    } else {
        // Validate phone number - must be exactly 10 digits starting with 0
        $clean_phone = preg_replace('/\D/', '', $phone);
        
        if (strlen($clean_phone) !== 10 || substr($clean_phone, 0, 1) !== '0') {
            $error_message = "Please enter a valid phone number. Must be exactly 10 digits starting with 0 (e.g., 0247965501).";
        } else {
            $phone = $clean_phone;
        }
        
        // Only proceed if phone validation passed
        if (empty($error_message)) {
            // Check if username already exists
            $check_username_stmt = $conn->prepare("SELECT id FROM agents WHERE username = ? LIMIT 1");
            $check_username_stmt->bind_param("s", $username);
            $check_username_stmt->execute();
            $username_result = $check_username_stmt->get_result();
            
            if ($username_result->num_rows > 0) {
                $error_message = "Username already exists. Please choose another.";
                $check_username_stmt->close();
            } else {
                $check_username_stmt->close();
                
                // Check if email already exists
                $check_email_stmt = $conn->prepare("SELECT id FROM agents WHERE email = ? LIMIT 1");
                $check_email_stmt->bind_param("s", $email);
                $check_email_stmt->execute();
                $email_result = $check_email_stmt->get_result();
                
                if ($email_result->num_rows > 0) {
                    $error_message = "Email already registered. Please use a different email or try logging in.";
                    $check_email_stmt->close();
                } else {
                    $check_email_stmt->close();
                    
                    // STRICT RULE: Check if user already has a store (prevent duplicate store owner registration)
                    $check_existing_store = $conn->prepare("SELECT id, is_store_owner, store_id FROM agents WHERE email = ? OR username = ? LIMIT 1");
                    $check_existing_store->bind_param("ss", $email, $username);
                    $check_existing_store->execute();
                    $existing_result = $check_existing_store->get_result();
                    
                    if ($existing_result->num_rows > 0) {
                        $existing_user = $existing_result->fetch_assoc();
                        $check_existing_store->close();
                        
                        if ($existing_user['is_store_owner'] == 1 || $existing_user['store_id'] !== null) {
                            $error_message = "This account already has a store. Please login instead.";
                        } else {
                            $error_message = "Account already exists. Please login instead.";
                        }
                    } else {
                        $check_existing_store->close();
                        
                        // Hash the password
                        $password_hash = password_hash($password, PASSWORD_BCRYPT);
                        
                        // STRICT RULE: Store owner registration - NO store_id, is_store_owner = 0 initially
                        // MULTI-LAYER: Role will be updated to 'store_owner' after store creation
                        $balance = 0.00;
                        $role = 'agent'; // Will be updated to 'store_owner' after store creation
                        $is_store_owner = 0; // Will be updated to 1 after store creation
                        $store_id = null; // Explicitly NULL for store owners during registration
                        
                        // Insert new agent WITHOUT store_id (store owners don't have store_id until store is created)
                        $stmt = $conn->prepare("INSERT INTO agents (username, email, phone, password_hash, balance, role, is_store_owner, store_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                        $stmt->bind_param("ssssdsii", $username, $email, $phone, $password_hash, $balance, $role, $is_store_owner, $store_id);
                        
                        if ($stmt->execute()) {
                            $newUserId = $conn->insert_id;
                            $stmt->close();
                            
                            // STRICT RULE: Create store for the new user (this will mark them as store owner)
                            require_once 'app/classes/StoreManager.php';
                            $storeManager = new StoreManager($conn);
                            
                            $storeName = $username . " Store";
                            $storeData = [
                                'phone' => $phone,
                                'email' => $email,
                                'description' => "Welcome to " . $username . "'s data bundle store!",
                                'status' => 'active'
                            ];
                            
                            $storeResult = $storeManager->createStore($storeName, $newUserId, $storeData);
                            
                            if ($storeResult['success']) {
                                // Verify store owner was marked correctly
                                $verify_stmt = $conn->prepare("SELECT is_store_owner, store_id FROM agents WHERE id = ?");
                                $verify_stmt->bind_param("i", $newUserId);
                                $verify_stmt->execute();
                                $verify_result = $verify_stmt->get_result();
                                $verify_user = $verify_result->fetch_assoc();
                                $verify_stmt->close();
                                
                                if ($verify_user['is_store_owner'] == 1 && $verify_user['store_id'] == $storeResult['store_id']) {
                                    // Store created successfully and user marked as store owner - redirect to setup
                                    $_SESSION['user_id'] = $newUserId;
                                    $_SESSION['role'] = $role;
                                    $_SESSION['username'] = $username;
                                    $_SESSION['new_store'] = true;
                                    $_SESSION['store_id'] = $storeResult['store_id'];
                                    
                                    header("Location: pages/store_setup.php");
                                    exit();
                                } else {
                                    // Store created but user not marked correctly - rollback
                                    $rollback_stmt = $conn->prepare("DELETE FROM stores WHERE id = ?");
                                    $rollback_stmt->bind_param("i", $storeResult['store_id']);
                                    $rollback_stmt->execute();
                                    $rollback_stmt->close();
                                    
                                    $rollback_user_stmt = $conn->prepare("DELETE FROM agents WHERE id = ?");
                                    $rollback_user_stmt->bind_param("i", $newUserId);
                                    $rollback_user_stmt->execute();
                                    $rollback_user_stmt->close();
                                    
                                    $error_message = "Registration failed. Please try again.";
                                }
                            } else {
                                // Store creation failed - delete the user account
                                $rollback_user_stmt = $conn->prepare("DELETE FROM agents WHERE id = ?");
                                $rollback_user_stmt->bind_param("i", $newUserId);
                                $rollback_user_stmt->execute();
                                $rollback_user_stmt->close();
                                
                                $error_message = "Failed to create store. Registration incomplete. Please try again.";
                            }
                        } else {
                            $error_message = "Registration failed. Please try again later.";
                            $stmt->close();
                        }
                    }
                }
            }
        }
    }
}

// Get contact configuration
require_once 'app/classes/ContactConfig.php';
$contactConfig = new ContactConfig($conn);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <title>Create Account | D-Bundles Stores</title>
    <meta name="description" content="Create your D-Bundles Stores agent account - secure, fast, and reliable data bundle management.">
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&family=Space+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        /* Enhanced Professional Dark Theme - Matching Login Page */
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .gradient-bg {
            background: linear-gradient(135deg, #1e293b 0%, #334155 50%, #475569 100%);
        }
        
        .logo-gradient {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
        }
        
        /* Minimal Professional Animations */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        
        .footer-link {
            transition: all 0.3s ease;
            position: relative;
        }
        
        .footer-link:hover {
            color: #93c5fd;
            transform: translateX(5px);
        }
    </style>
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        'poppins': ['Poppins', 'sans-serif'],
                        'space': ['Space Grotesk', 'sans-serif'],
                    },
                    colors: {
                        primary: {
                            50: '#f0f9ff',
                            100: '#e0f2fe',
                            200: '#bae6fd',
                            300: '#7dd3fc',
                            400: '#38bdf8',
                            500: '#0ea5e9',
                            600: '#0284c7',
                            700: '#0369a1',
                            800: '#075985',
                            900: '#0c4a6e',
                        },
                        dark: {
                            50: '#f8fafc',
                            100: '#f1f5f9',
                            200: '#e2e8f0',
                            300: '#cbd5e1',
                            400: '#94a3b8',
                            500: '#64748b',
                            600: '#475569',
                            700: '#334155',
                            800: '#1e293b',
                            900: '#0f172a',
                        }
                    }
                }
            }
        }
    </script>
</head>

<body>
    <div class="min-h-screen flex items-center justify-center px-4 sm:px-6 py-4">
        <div class="w-full max-w-md">
            <!-- Logo and Branding -->
            <div class="text-center mb-4">
                <div class="flex items-center justify-center mb-2">
                    <div class="w-10 h-10 logo-gradient rounded-xl flex items-center justify-center mr-2 shadow-lg">
                        <i class="fas fa-bolt text-white text-lg"></i>
                    </div>
                    <div class="text-left">
                        <h1 class="text-lg font-bold text-white">D-Bundles Stores</h1>
                        <p class="text-gray-400 text-xs font-normal">Agent Portal</p>
                    </div>
                </div>
            </div>

            <!-- Registration Form -->
            <div class="bg-gray-800 rounded-lg p-5 shadow-2xl border border-gray-700">
                <div class="text-center mb-4">
                    <div class="w-10 h-10 bg-blue-600 rounded-full flex items-center justify-center mx-auto mb-2">
                        <i class="fas fa-user-plus text-white text-lg"></i>
                    </div>
                    <h2 class="text-lg font-bold text-white mb-0.5">Create Account</h2>
                    <p class="text-gray-400 text-xs">Sign up to become an agent</p>
                </div>

                <form method="POST" class="space-y-3">
                    <!-- Error/Success Messages -->
                    <?php if (!empty($error_message)): ?>
                    <div class="bg-red-900 border border-red-700 text-red-300 px-3 py-2 rounded mb-4 text-sm">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        <?php echo htmlspecialchars($error_message); ?>
                    </div>
                    <?php endif; ?>

                    <?php if (!empty($success_message)): ?>
                    <div class="bg-green-900 border border-green-700 text-green-300 px-3 py-2 rounded mb-4 text-sm">
                        <i class="fas fa-check-circle mr-2"></i>
                        <?php echo htmlspecialchars($success_message); ?>
                    </div>
                    <?php endif; ?>

                    <!-- Username Field -->
                    <div>
                        <label for="username" class="block text-xs font-medium text-gray-400 mb-1">
                            Username
                        </label>
                        <div class="relative">
                            <input 
                                id="username" 
                                name="username" 
                                type="text" 
                                required 
                                minlength="3"
                                class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-3 py-2 pl-9 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 placeholder-gray-400"
                                placeholder="Choose username"
                                value="<?php echo htmlspecialchars($username ?? ''); ?>"
                                autocomplete="username"
                            >
                            <div class="absolute inset-y-0 left-0 flex items-center pl-2.5">
                                <i class="fas fa-user text-gray-500 text-xs"></i>
                            </div>
                        </div>
                    </div>

                    <!-- Email Field -->
                    <div>
                        <label for="email" class="block text-xs font-medium text-gray-400 mb-1">
                            Email
                        </label>
                        <div class="relative">
                            <input 
                                id="email" 
                                name="email" 
                                type="email" 
                                required 
                                class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-3 py-2 pl-9 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 placeholder-gray-400"
                                placeholder="your@email.com"
                                value="<?php echo htmlspecialchars($email ?? ''); ?>"
                                autocomplete="email"
                            >
                            <div class="absolute inset-y-0 left-0 flex items-center pl-2.5">
                                <i class="fas fa-envelope text-gray-500 text-xs"></i>
                            </div>
                        </div>
                    </div>

                    <!-- Phone Field -->
                    <div>
                        <label for="phone" class="block text-xs font-medium text-gray-400 mb-1">
                            Phone Number
                        </label>
                        <div class="relative">
                            <input 
                                id="phone" 
                                name="phone" 
                                type="tel" 
                                required 
                                pattern="[0-9]{10}"
                                maxlength="10"
                                class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-3 py-2 pl-9 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 placeholder-gray-400"
                                placeholder="0247965501"
                                value="<?php echo htmlspecialchars($phone ?? ''); ?>"
                                autocomplete="tel"
                            >
                            <div class="absolute inset-y-0 left-0 flex items-center pl-2.5">
                                <i class="fas fa-phone text-gray-500 text-xs"></i>
                            </div>
                        </div>
                        <p class="text-xs text-gray-500 mt-0.5">Ghana phone number (e.g., 0247965501)</p>
                    </div>

                    <!-- Password Field -->
                    <div>
                        <label for="password" class="block text-xs font-medium text-gray-400 mb-1">
                            Password
                        </label>
                        <div class="relative">
                            <input 
                                id="password" 
                                name="password" 
                                type="password" 
                                required 
                                minlength="6"
                                class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-3 py-2 pl-9 pr-9 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 placeholder-gray-400"
                                placeholder="Enter password"
                                autocomplete="new-password"
                            >
                            <div class="absolute inset-y-0 left-0 flex items-center pl-2.5">
                                <i class="fas fa-lock text-gray-500 text-xs"></i>
                            </div>
                            <button type="button" onclick="togglePassword('password', 'passwordToggle')" class="absolute inset-y-0 right-0 flex items-center pr-2.5 text-gray-500 hover:text-amber-400 transition-colors">
                                <i id="passwordToggle" class="fas fa-eye text-xs"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Confirm Password Field -->
                    <div>
                        <label for="confirm_password" class="block text-xs font-medium text-gray-400 mb-1">
                            Confirm Password
                        </label>
                        <div class="relative">
                            <input 
                                id="confirm_password" 
                                name="confirm_password" 
                                type="password" 
                                required 
                                minlength="6"
                                class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg px-3 py-2 pl-9 pr-9 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 placeholder-gray-400"
                                placeholder="Confirm password"
                                autocomplete="new-password"
                            >
                            <div class="absolute inset-y-0 left-0 flex items-center pl-2.5">
                                <i class="fas fa-lock text-gray-500 text-xs"></i>
                            </div>
                            <button type="button" onclick="togglePassword('confirm_password', 'confirmPasswordToggle')" class="absolute inset-y-0 right-0 flex items-center pr-2.5 text-gray-500 hover:text-amber-400 transition-colors">
                                <i id="confirmPasswordToggle" class="fas fa-eye text-xs"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Submit Button -->
                    <button 
                        type="submit" 
                        class="w-full bg-blue-600 text-white py-2.5 rounded-lg font-medium hover:bg-blue-700 transition-colors text-sm mt-4"
                    >
                        <i class="fas fa-user-plus mr-2"></i>
                        Create Account
                    </button>
                </form>

                <!-- Navigation Links -->
                <div class="mt-4 space-y-2">
                    <a href="index.php" class="w-full bg-gray-600 text-white py-2 rounded-lg text-sm font-medium hover:bg-gray-700 transition-colors flex items-center justify-center">
                        <i class="fas fa-home mr-2"></i>Back to Home
                    </a>
                </div>

                <!-- Login Link -->
                <div class="mt-3 text-center">
                    <p class="text-xs text-gray-400">
                        Already have an account? 
                        <a href="login.php" class="text-blue-400 hover:text-blue-300 transition-colors font-medium">
                            Sign In
                        </a>
                    </p>
                </div>
            </div>
        </div>
    </div>

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

        // Phone number validation
        document.addEventListener('DOMContentLoaded', function() {
            const phoneInput = document.getElementById('phone');
            
            if (phoneInput) {
                phoneInput.addEventListener('input', function() {
                    // Remove any non-digit characters
                    this.value = this.value.replace(/\D/g, '');
                    // Limit to 10 digits
                    if (this.value.length > 10) {
                        this.value = this.value.substring(0, 10);
                    }
                    
                    // Validate format
                    const phone = this.value.trim();
                    this.classList.remove('border-red-500', 'border-green-500');
                    
                    if (phone.length === 10 && phone.charAt(0) === '0') {
                        this.classList.add('border-green-500');
                    } else if (phone.length > 0) {
                        this.classList.add('border-red-500');
                    }
                });
                
                phoneInput.addEventListener('blur', function() {
                    const phone = this.value.trim();
                    if (phone.length > 0 && (phone.length !== 10 || phone.charAt(0) !== '0')) {
                        this.classList.add('border-red-500');
                    }
                });
            }
            
            // Add focus effects to form inputs
            const inputs = document.querySelectorAll('input[type="text"], input[type="email"], input[type="password"]');
            inputs.forEach(input => {
                input.addEventListener('focus', function() {
                    this.parentElement.classList.add('ring-2', 'ring-primary-500');
                });
                
                input.addEventListener('blur', function() {
                    this.parentElement.classList.remove('ring-2', 'ring-primary-500');
                });
            });

            // Add loading state to submit button
            const form = document.querySelector('form');
            const submitBtn = document.querySelector('button[type="submit"]');
            
            form.addEventListener('submit', function(e) {
                const phone = phoneInput.value.trim();
                if (phone.length !== 10 || phone.charAt(0) !== '0') {
                    e.preventDefault();
                    alert('Please enter a valid phone number. Must be exactly 10 digits starting with 0 (e.g., 0247965501).');
                    phoneInput.focus();
                    return false;
                }
                
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Creating Account...';
                submitBtn.disabled = true;
            });
        });
    </script>
</body>
</html>

