<?php
/**
 * Registration Page
 * LandSales Pro - New subscriber registration with trial subscription
 */
define('APP_RUNNING', true);
require_once 'db_connect.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'includes/subscription.php';
require_once 'includes/track.php';

initSecureSession();

// Redirect if already logged in
if (isAuthenticated() && validateSession()) {
    header('Location: dashboard/');
    exit;
}

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

// Get plans for display
$plans = getAllPlans();
$selected_plan = $_GET['plan'] ?? 'starter';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $csrf_token = $_POST['csrf_token'] ?? '';

    if (!verifyCSRFToken($csrf_token)) {
        $error = 'Security token expired. Please try again.';
    } else {
        // Get form data
        $full_name = sanitizeInput($_POST['full_name'] ?? '');
        $company_name = sanitizeInput($_POST['company_name'] ?? '');
        $email = sanitizeInput($_POST['email'] ?? '');
        $phone = sanitizeInput($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        $plan_id = intval($_POST['plan_id'] ?? 1);

        // Normalize phone number
        $phone = preg_replace('/[^0-9]/', '', $phone);
        if (strlen($phone) == 9) {
            $phone = '0' . $phone;
        } elseif (strlen($phone) == 12 && substr($phone, 0, 3) == '255') {
            $phone = '0' . substr($phone, 3);
        }

        // Validation
        if (empty($full_name)) {
            $error = 'Please enter your full name';
        } elseif (empty($company_name)) {
            $error = 'Please enter your company/business name';
        } elseif (!isValidEmail($email)) {
            $error = 'Please enter a valid email address';
        } elseif (!isValidPhone($phone)) {
            $error = 'Please enter a valid phone number';
        } elseif (strlen($password) < PASSWORD_MIN_LENGTH) {
            $error = 'Password must be at least ' . PASSWORD_MIN_LENGTH . ' characters';
        } elseif ($password !== $confirm_password) {
            $error = 'Passwords do not match';
        } else {
            // Check if email exists
            $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            if ($stmt->get_result()->num_rows > 0) {
                $error = 'Email already registered. Please login or use a different email.';
            } else {
                // Check if phone exists
                $stmt = $conn->prepare("SELECT id FROM users WHERE phone = ?");
                $stmt->bind_param("s", $phone);
                $stmt->execute();
                if ($stmt->get_result()->num_rows > 0) {
                    $error = 'Phone number already registered.';
                } else {
                    // Create user
                    $hashed_password = hashPassword($password);
                    $status = 'active'; // Auto-activate for trial

                    $stmt = $conn->prepare("INSERT INTO users (email, phone, password, full_name, company_name, role, status) VALUES (?, ?, ?, ?, ?, 'subscriber', ?)");
                    $stmt->bind_param("ssssss", $email, $phone, $hashed_password, $full_name, $company_name, $status);

                    if ($stmt->execute()) {
                        $user_id = $conn->insert_id;

                        // Create trial subscription
                        $plan = getPlanById($plan_id) ?: getPlanById(1);
                        $trial_days = TRIAL_DAYS;
                        $starts_at = date('Y-m-d H:i:s');
                        $expires_at = date('Y-m-d H:i:s', strtotime("+{$trial_days} days"));

                        $stmt = $conn->prepare("INSERT INTO subscriptions (user_id, plan_id, billing_cycle, amount, status, starts_at, expires_at, trial_ends_at) VALUES (?, ?, 'monthly', 0, 'trial', ?, ?, ?)");
                        $stmt->bind_param("iisss", $user_id, $plan_id, $starts_at, $expires_at, $expires_at);
                        $stmt->execute();

                        // Log registration
                        logActivity($user_id, 'registration', "New subscriber registered: {$company_name}");

                        // Redirect to login
                        header('Location: login.php?success=registered');
                        exit;
                    } else {
                        $error = 'Registration failed. Please try again.';
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Account - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/font-awesome/css/all.min.css">
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * { font-family: 'Inter', sans-serif; }
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .register-wrapper {
            display: flex;
            align-items: stretch;
            width: 100%;
            max-width: 900px;
            background: white;
            border-radius: 20px;
            box-shadow: 0 25px 50px rgba(0,0,0,0.25);
            overflow: hidden;
        }
        .register-info {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            display: none;
            flex-direction: column;
            justify-content: center;
        }
        @media (min-width: 768px) {
            .register-info {
                display: flex;
                width: 40%;
            }
            .register-container {
                width: 60%;
            }
        }
        .register-info h2 {
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 15px;
        }
        .register-info p {
            opacity: 0.9;
            margin-bottom: 30px;
        }
        .trial-badge {
            background: rgba(255,255,255,0.2);
            padding: 15px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
        }
        .trial-badge i {
            font-size: 24px;
            margin-bottom: 10px;
        }
        .trial-badge h4 {
            font-size: 1.1rem;
            margin-bottom: 5px;
        }
        .trial-badge p {
            font-size: 14px;
            margin: 0;
            opacity: 0.9;
        }
        .register-container {
            padding: 40px;
            width: 100%;
        }
        .register-header {
            text-align: center;
            margin-bottom: 25px;
        }
        .register-header .logo {
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
        }
        .register-header .logo i {
            font-size: 28px;
            color: white;
        }
        .register-header h2 {
            color: #1a1d21;
            font-weight: 700;
            font-size: 1.4rem;
            margin-bottom: 5px;
        }
        .register-header p {
            color: #6b7280;
            font-size: 14px;
        }
        .form-group {
            margin-bottom: 18px;
        }
        .form-group label {
            font-weight: 500;
            color: #374151;
            margin-bottom: 6px;
            font-size: 14px;
        }
        .form-control {
            border-radius: 10px;
            padding: 12px 15px;
            border: 2px solid #e5e7eb;
            font-size: 14px;
            transition: all 0.3s ease;
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
        }
        .row-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        @media (max-width: 500px) {
            .row-2 { grid-template-columns: 1fr; }
        }
        .btn-register {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            border-radius: 10px;
            padding: 14px;
            font-weight: 600;
            font-size: 15px;
            width: 100%;
            color: white;
            transition: all 0.3s ease;
        }
        .btn-register:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
            color: white;
        }
        .login-link {
            text-align: center;
            margin-top: 20px;
        }
        .login-link p {
            color: #6b7280;
            margin-bottom: 0;
            font-size: 14px;
        }
        .login-link a {
            color: #667eea;
            font-weight: 600;
            text-decoration: none;
        }
        .alert {
            border-radius: 10px;
            padding: 12px 15px;
            margin-bottom: 20px;
            border: none;
            font-size: 14px;
        }
        .alert-danger {
            background: #fef2f2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
        .plan-selector {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 10px;
            margin-bottom: 20px;
        }
        @media (max-width: 500px) {
            .plan-selector { grid-template-columns: 1fr; }
        }
        .plan-option {
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            padding: 12px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .plan-option:hover {
            border-color: #667eea;
        }
        .plan-option.selected {
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.05);
        }
        .plan-option input {
            display: none;
        }
        .plan-option h5 {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 5px;
            color: #374151;
        }
        .plan-option .price {
            font-size: 12px;
            color: #6b7280;
        }
    </style>
</head>
<body>
    <div class="register-wrapper">
        <div class="register-info">
            <h2><?php echo APP_NAME; ?></h2>
            <p>The complete solution for managing your land sales business</p>

            <div class="trial-badge">
                <i class="fas fa-gift"></i>
                <h4><?php echo TRIAL_DAYS; ?> Days Free Trial</h4>
                <p>No credit card required. Full access to all features.</p>
            </div>

            <div class="trial-badge">
                <i class="fas fa-chart-line"></i>
                <h4>Grow Your Business</h4>
                <p>Track plots, sales, payments, and profits effortlessly.</p>
            </div>
        </div>

        <div class="register-container">
            <div class="register-header">
                <div class="logo">
                    <i class="fas fa-map-marked-alt"></i>
                </div>
                <h2>Create Your Account</h2>
                <p>Start your <?php echo TRIAL_DAYS; ?>-day free trial</p>
            </div>

            <?php if ($error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
            </div>
            <?php endif; ?>

            <form action="" method="POST" id="registerForm">
                <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">

                <div class="row-2">
                    <div class="form-group">
                        <label for="full_name">Full Name</label>
                        <input type="text" name="full_name" id="full_name" class="form-control"
                               placeholder="John Doe" required
                               value="<?php echo htmlspecialchars($_POST['full_name'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label for="company_name">Company/Business Name</label>
                        <input type="text" name="company_name" id="company_name" class="form-control"
                               placeholder="Green Valley Properties" required
                               value="<?php echo htmlspecialchars($_POST['company_name'] ?? ''); ?>">
                    </div>
                </div>

                <div class="row-2">
                    <div class="form-group">
                        <label for="email">Email Address</label>
                        <input type="email" name="email" id="email" class="form-control"
                               placeholder="john@example.com" required
                               value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
                    </div>
                    <div class="form-group">
                        <label for="phone">Phone Number</label>
                        <input type="tel" name="phone" id="phone" class="form-control"
                               placeholder="0712 345 678" required
                               value="<?php echo htmlspecialchars($_POST['phone'] ?? ''); ?>">
                    </div>
                </div>

                <div class="row-2">
                    <div class="form-group">
                        <label for="password">Password</label>
                        <input type="password" name="password" id="password" class="form-control"
                               placeholder="Min <?php echo PASSWORD_MIN_LENGTH; ?> characters" required>
                    </div>
                    <div class="form-group">
                        <label for="confirm_password">Confirm Password</label>
                        <input type="password" name="confirm_password" id="confirm_password" class="form-control"
                               placeholder="Confirm password" required>
                    </div>
                </div>

                <label class="mb-2" style="font-weight: 500; color: #374151; font-size: 14px;">Select Plan</label>
                <div class="plan-selector">
                    <?php foreach ($plans as $plan): ?>
                    <label class="plan-option <?php echo $plan['slug'] === $selected_plan ? 'selected' : ''; ?>">
                        <input type="radio" name="plan_id" value="<?php echo $plan['id']; ?>"
                               <?php echo $plan['slug'] === $selected_plan ? 'checked' : ''; ?>>
                        <h5><?php echo htmlspecialchars($plan['name']); ?></h5>
                        <div class="price"><?php echo formatMoney($plan['price_monthly']); ?>/mo</div>
                    </label>
                    <?php endforeach; ?>
                </div>

                <button type="submit" class="btn btn-register" id="registerBtn">
                    <span class="btn-text">Start Free Trial</span>
                </button>

                <p class="text-center text-muted mt-3" style="font-size: 12px;">
                    By creating an account, you agree to our Terms of Service and Privacy Policy
                </p>
            </form>

            <div class="login-link">
                <p>Already have an account? <a href="login.php">Sign In</a></p>
            </div>
        </div>
    </div>

    <script src="assets/vendor/jquery/jquery.min.js"></script>
    <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        // Plan selection
        document.querySelectorAll('.plan-option').forEach(function(option) {
            option.addEventListener('click', function() {
                document.querySelectorAll('.plan-option').forEach(function(o) {
                    o.classList.remove('selected');
                });
                this.classList.add('selected');
                this.querySelector('input').checked = true;
            });
        });

        // Form submission
        document.getElementById('registerForm').addEventListener('submit', function() {
            const btn = document.getElementById('registerBtn');
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Creating Account...';
            btn.disabled = true;
        });
    </script>
</body>
</html>
