<?php
/**
 * Register as Agent under a specific store
 */

session_start();
require_once 'config.php';
require_once 'app/classes/StoreManager.php';

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

// Get store slug from URL
$storeSlug = $_GET['store'] ?? '';

if (empty($storeSlug)) {
    header("Location: index.php");
    exit();
}

// STRICT RULE: Load store and verify it exists and is active
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreBySlug($storeSlug);

if (!$store) {
    header("Location: 404.php");
    exit();
}

// STRICT RULE: Verify store is active (prevent registration to inactive stores)
if (isset($store['status']) && $store['status'] !== 'active') {
    $error_message = "This store is currently inactive. Registration is not available at this time.";
}

// Ensure email and password_hash columns exist
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;
}

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");
    }
} 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;
        }
        
        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 exists and has a store (prevent store owners from registering as sub-agents)
                    $check_existing_user = $conn->prepare("SELECT id, is_store_owner, store_id FROM agents WHERE email = ? OR username = ? LIMIT 1");
                    $check_existing_user->bind_param("ss", $email, $username);
                    $check_existing_user->execute();
                    $existing_user_result = $check_existing_user->get_result();
                    
                    if ($existing_user_result->num_rows > 0) {
                        $existing_user = $existing_user_result->fetch_assoc();
                        $check_existing_user->close();
                        
                        if ($existing_user['is_store_owner'] == 1) {
                            $error_message = "Store owners cannot register as sub-agents. Please login to your store owner account.";
                        } elseif ($existing_user['store_id'] !== null && $existing_user['store_id'] != $store['id']) {
                            $error_message = "You are already registered under another store. Please login instead.";
                        } elseif ($existing_user['store_id'] == $store['id']) {
                            $error_message = "You are already registered as an agent for this store. Please login instead.";
                        } else {
                            $error_message = "Account already exists. Please login instead.";
                        }
                    } else {
                        $check_existing_user->close();
                        
                        // STRICT RULE: Verify store exists and is active
                        if ($store['status'] !== 'active') {
                            $error_message = "This store is currently inactive. Registration is not available.";
                        } else {
                            // Hash the password
                            $password_hash = password_hash($password, PASSWORD_BCRYPT);
                            
                            // STRICT RULE: Sub-agent registration - MUST have store_id, is_store_owner = 0
                            $balance = 0.00;
                            $role = 'agent';
                            $is_store_owner = 0; // Explicitly 0 for sub-agents
                            
                            // Insert new agent WITH store_id (sub-agents belong to a store)
                            $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()) {
                                $newAgentId = $conn->insert_id;
                                $stmt->close();
                                
                                // STRICT RULE: Verify agent was created correctly
                                $verify_stmt = $conn->prepare("SELECT is_store_owner, store_id FROM agents WHERE id = ?");
                                $verify_stmt->bind_param("i", $newAgentId);
                                $verify_stmt->execute();
                                $verify_result = $verify_stmt->get_result();
                                $verify_agent = $verify_result->fetch_assoc();
                                $verify_stmt->close();
                                
                                if ($verify_agent['is_store_owner'] == 0 && $verify_agent['store_id'] == $store['id']) {
                                    // Add to store_agents junction table
                                    $addResult = $storeManager->addAgentToStore($store['id'], $newAgentId, 'agent');
                                    
                                    // CRITICAL FIX: Verify agent still has correct role after addAgentToStore
                                    // This prevents any database triggers or side effects from changing is_store_owner
                                    if ($addResult['success']) {
                                        $final_verify_stmt = $conn->prepare("SELECT is_store_owner, store_id, role FROM agents WHERE id = ?");
                                        $final_verify_stmt->bind_param("i", $newAgentId);
                                        $final_verify_stmt->execute();
                                        $final_verify_result = $final_verify_stmt->get_result();
                                        $final_verify_agent = $final_verify_result->fetch_assoc();
                                        $final_verify_stmt->close();
                                        
                                        // Ensure agent is still correctly configured as sub-agent
                                        if ($final_verify_agent['is_store_owner'] == 0 && 
                                            $final_verify_agent['store_id'] == $store['id'] && 
                                            $final_verify_agent['role'] == 'agent') {
                                    // Redirect to login
                                    header("Location: login.php?registered=1&agent=1");
                                    exit();
                                        } else {
                                            // Agent role was changed incorrectly - rollback
                                            $rollback_stmt = $conn->prepare("DELETE FROM agents WHERE id = ?");
                                            $rollback_stmt->bind_param("i", $newAgentId);
                                            $rollback_stmt->execute();
                                            $rollback_stmt->close();
                                            
                                            // Also remove from store_agents if it was added
                                            $remove_stmt = $conn->prepare("DELETE FROM store_agents WHERE agent_id = ?");
                                            $remove_stmt->bind_param("i", $newAgentId);
                                            $remove_stmt->execute();
                                            $remove_stmt->close();
                                            
                                            $error_message = "Registration failed: Role assignment error. Please try again.";
                                        }
                                    } else {
                                        // Failed to add to store - rollback agent creation
                                        $rollback_stmt = $conn->prepare("DELETE FROM agents WHERE id = ?");
                                        $rollback_stmt->bind_param("i", $newAgentId);
                                        $rollback_stmt->execute();
                                        $rollback_stmt->close();
                                        
                                        $error_message = "Registration failed: " . ($addResult['message'] ?? 'Unknown error');
                                    }
                                } else {
                                    // Agent created incorrectly - rollback
                                    $rollback_stmt = $conn->prepare("DELETE FROM agents WHERE id = ?");
                                    $rollback_stmt->bind_param("i", $newAgentId);
                                    $rollback_stmt->execute();
                                    $rollback_stmt->close();
                                    
                                    $error_message = "Registration failed. Please try again.";
                                }
                            } else {
                                $error_message = "Registration failed. Please try again later.";
                                $stmt->close();
                            }
                        }
                    }
                }
            }
        }
    }
}
?>
<!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>Register as Agent - <?php echo htmlspecialchars($store['store_name']); ?></title>
    
    <!-- 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">
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;I said well 
            display: flex;
            flex-direction: column;
        }
        
        .gradient-bg {
            background: linear-gradient(135deg, #1e293b 0%, #334155 50%, #475569 100%);understand
        }
        
        .logo-gradient {
            background: linear-gradient(135deg, #3b82f6 0%, #8b5cf6 100%);
        }
    </style>
</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">
            <!-- Store Info -->
            <div class="text-center mb-6">
                <div class="flex items-center justify-center mb-4">
                    <?php if (!empty($store['logo_url'])): ?>
                    <img src="<?php echo htmlspecialchars($store['logo_url']); ?>" 
                         alt="<?php echo htmlspecialchars($store['store_name']); ?>" 
                         class="w-16 h-16 rounded-full border-4 border-blue-500">
                    <?php else: ?>
                    <div class="w-16 h-16 logo-gradient rounded-full flex items-center justify-center">
                        <i class="fas fa-store text-white text-2xl"></i>
                    </div>
                    <?php endif; ?>
                </div>
                <h1 class="text-2xl font-bold text-white mb-2">
                    Join <?php echo htmlspecialchars($store['store_name']); ?>
                </h1>
                <p class="text-gray-400 text-sm">Register as an agent and start selling data</p>
            </div>

            <!-- Registration Form -->
            <div class="bg-gray-800 rounded-lg p-6 shadow-2xl border border-gray-700">
                <h2 class="text-lg font-bold text-white mb-4 text-center">
                    <i class="fas fa-user-plus text-blue-400 mr-2"></i>
                    Create Agent Account
                </h2>

                <form method="POST" class="space-y-3">
                    <!-- Error Message -->
                    <?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; ?>

                    <!-- Username Field -->
                    <div>
                        <label for="username" class="block text-xs font-medium text-gray-400 mb-1">
                            Username
                        </label>
                        <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 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                            placeholder="Choose username"
                            value="<?php echo htmlspecialchars($username ?? ''); ?>"
                        >
                    </div>

                    <!-- Email Field -->
                    <div>
                        <label for="email" class="block text-xs font-medium text-gray-400 mb-1">
                            Email
                        </label>
                        <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 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                            placeholder="your@email.com"
                            value="<?php echo htmlspecialchars($email ?? ''); ?>"
                        >
                    </div>

                    <!-- Phone Field -->
                    <div>
                        <label for="phone" class="block text-xs font-medium text-gray-400 mb-1">
                            Phone Number
                        </label>
                        <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 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                            placeholder="0247965501"
                            value="<?php echo htmlspecialchars($phone ?? ''); ?>"
                        >
                        <p class="text-xs text-gray-500 mt-0.5">Enter 10-digit 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>
                        <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 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                            placeholder="Enter password"
                        >
                    </div>

                    <!-- Confirm Password Field -->
                    <div>
                        <label for="confirm_password" class="block text-xs font-medium text-gray-400 mb-1">
                            Confirm Password
                        </label>
                        <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 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                            placeholder="Confirm password"
                        >
                    </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>
                        Register as Agent
                    </button>
                </form>

                <!-- Links -->
                <div class="mt-4 space-y-2 text-center text-xs">
                    <p class="text-gray-400">
                        Already have an account? 
                        <a href="login.php" class="text-blue-400 hover:text-blue-300 font-medium">
                            Sign In
                        </a>
                    </p>
                    <p class="text-gray-400">
                        <a href="store.php?slug=<?php echo urlencode($storeSlug); ?>" class="text-blue-400 hover:text-blue-300 font-medium">
                            <i class="fas fa-arrow-left mr-1"></i>
                            Back to Store
                        </a>
                    </p>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Phone number validation
        document.addEventListener('DOMContentLoaded', function() {
            const phoneInput = document.getElementById('phone');
            const form = document.querySelector('form');
            
            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');
                    }
                });
            }
            
            if (form) {
                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;
                    }
                });
            }
        });
    </script>
</body>
</html>



