<?php
session_start();
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/Billing/SubscriptionManager.php';
require_once __DIR__ . '/../src/SuperAdmin/PlatformSettings.php';

// Get trial settings
$trialEnabled = PlatformSettings::get('trial_enabled', true);
$trialDays = (int) PlatformSettings::get('trial_days', 14);
$trialApplyTo = PlatformSettings::get('trial_apply_to', 'all');
$trialPlanId = (int) PlatformSettings::get('trial_plan_id', 1);

// Detect currency from session, cookie, or default
$selectedCurrency = $_GET['currency'] ?? $_SESSION['currency'] ?? $_COOKIE['currency'] ?? 'USD';
if (!in_array($selectedCurrency, ['USD', 'INR'])) {
    $selectedCurrency = 'USD';
}
$_SESSION['currency'] = $selectedCurrency;
setcookie('currency', $selectedCurrency, time() + 86400 * 365, '/');

$currencySymbol = $selectedCurrency === 'INR' ? '₹' : '$';
$isIndia = $selectedCurrency === 'INR';

// Get selected plan from URL
$selectedPlanId = (int) ($_GET['plan'] ?? 0);
$selectedCycle = ($_GET['cycle'] ?? 'monthly') === 'yearly' ? 'yearly' : 'monthly';
if (!$selectedPlanId) {
    header('Location: /signup-plans.php');
    exit;
}

$plan = SubscriptionManager::getPlan($selectedPlanId);
$subscriptionPlans = SubscriptionManager::getPlans();

if (!$plan) {
    header('Location: /signup-plans.php');
    exit;
}

// Get price based on currency
if ($selectedCurrency === 'INR') {
    $displayPrice = $selectedCycle === 'yearly'
        ? ($plan['price_yearly_inr'] ?? $plan['price_yearly'] * 83)
        : ($plan['price_monthly_inr'] ?? $plan['price_monthly'] * 83);
} else {
    $displayPrice = $selectedCycle === 'yearly'
        ? $plan['price_yearly']
        : $plan['price_monthly'];
}
$displayLabel = $selectedCycle === 'yearly'
    ? 'per year (billed annually)'
    : 'per month';

$errors = [];
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selectedCycle = ($_POST['billing_cycle'] ?? $selectedCycle) === 'yearly' ? 'yearly' : 'monthly';
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $companyName = trim($_POST['company_name'] ?? '');
    $companyUsername = trim($_POST['company_username'] ?? '');

    // Validation
    if (empty($name)) $errors[] = "Name is required";
    if (empty($email)) $errors[] = "Email is required";
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Invalid email format";
    if (empty($password)) $errors[] = "Password is required";
    if (strlen($password) < 8) $errors[] = "Password must be at least 8 characters";
    if ($password !== $confirmPassword) $errors[] = "Passwords do not match";
    if (empty($companyName)) $errors[] = "Company name is required";
    if (empty($companyUsername)) $errors[] = "Company username is required";
    if (!preg_match('/^[a-zA-Z0-9_-]+$/', $companyUsername)) $errors[] = "Company username can only contain letters, numbers, _ and -";
    if (strlen($companyUsername) < 3 || strlen($companyUsername) > 20) $errors[] = "Company username must be 3-20 characters";

    if (empty($errors)) {
        try {
            $pdo = getPDO();
            
            // Check if email already exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $errors[] = "Email already exists";
            }

            // Check if company username already exists
            $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
            $stmt->execute([$companyUsername]);
            if ($stmt->fetch()) {
                $errors[] = "Company username already exists";
            }

            if (empty($errors)) {
                $pdo->beginTransaction();
                
                try {
                    // Check if this specific plan has trial
                    $thisPlanHasTrial = $trialEnabled && $trialDays > 0 && 
                        ($trialApplyTo === 'all' || $selectedPlanId === $trialPlanId);
                    
                    // Determine subscription status and expiry based on trial settings
                    $subscriptionStatus = $thisPlanHasTrial ? 'trial' : 'active';
                    $trialEndsAt = $thisPlanHasTrial 
                        ? date('Y-m-d H:i:s', strtotime("+{$trialDays} days"))
                        : null;
                    $subscriptionExpiresAt = $thisPlanHasTrial
                        ? $trialEndsAt
                        : date('Y-m-d H:i:s', strtotime($selectedCycle === 'yearly' ? '+1 year' : '+1 month'));

                    // Create company first (without owner_id initially)
                    $stmt = $pdo->prepare("INSERT INTO companies (name, username, subdomain, plan_id, subscription_status, subscription_expires_at, billing_cycle, preferred_currency, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                    $stmt->execute([$companyName, $companyUsername, $companyUsername, $selectedPlanId, $subscriptionStatus, $subscriptionExpiresAt, $selectedCycle, $selectedCurrency]);
                    $companyId = $pdo->lastInsertId();

                    // Create user with company_id
                    $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                    $stmt = $pdo->prepare("INSERT INTO users (name, email, password_hash, company_id, role, email_verified_at, created_at) VALUES (?, ?, ?, ?, 'admin', NOW(), NOW())");
                    $stmt->execute([$name, $email, $hashedPassword, $companyId]);
                    $userId = $pdo->lastInsertId();

                    // Update company with owner_id
                    $stmt = $pdo->prepare("UPDATE companies SET owner_id = ? WHERE id = ?");
                    $stmt->execute([$userId, $companyId]);

                    // Create subscription with trial support
                    $currentPeriodStart = date('Y-m-d H:i:s');
                    $currentPeriodEnd = $thisPlanHasTrial
                        ? $trialEndsAt
                        : date('Y-m-d H:i:s', strtotime($selectedCycle === 'yearly' ? '+1 year' : '+1 month'));
                    
                    $stmt = $pdo->prepare("INSERT INTO subscriptions (company_id, plan_id, status, billing_cycle, current_period_start, current_period_end, trial_ends_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
                    $stmt->execute([$companyId, $selectedPlanId, $subscriptionStatus, $selectedCycle, $currentPeriodStart, $currentPeriodEnd, $trialEndsAt]);

                    // Add user to user_company_access table (for workspace access)
                    $stmt = $pdo->prepare("INSERT INTO user_company_access (user_id, company_id, role, created_at) VALUES (?, ?, 'admin', NOW())");
                    $stmt->execute([$userId, $companyId]);

                    // Create company folder with subfolders
                    $companyFolder = __DIR__ . '/../storage/companies/' . $companyId;
                    if (!is_dir($companyFolder)) {
                        mkdir($companyFolder, 0755, true);
                        
                        // Create essential subfolders
                        $subfolders = [
                            'contracts',
                            'proposals', 
                            'clients',
                            'invoices',
                            'templates',
                            'uploads'
                        ];
                        
                        foreach ($subfolders as $subfolder) {
                            $subfolderPath = $companyFolder . '/' . $subfolder;
                            if (!is_dir($subfolderPath)) {
                                mkdir($subfolderPath, 0755, true);
                            }
                        }
                    }

                    $pdo->commit();

                    // If this plan has trial, go directly to dashboard
                    // Otherwise, redirect to checkout for payment
                    if ($thisPlanHasTrial) {
                        // Auto-login user for trial
                        $_SESSION['user_id'] = $userId;
                        $_SESSION['current_company_id'] = $companyId;
                        $_SESSION['current_company'] = [
                            'id' => $companyId,
                            'name' => $companyName,
                            'username' => $companyUsername,
                            'billing_cycle' => $selectedCycle
                        ];

                        AuthManager::login($email, $password);
                        header('Location: /index.php?welcome=1&workspace=' . urlencode($companyUsername));
                        exit;
                    } else {
                        // Store pending signup for checkout
                        $_SESSION['pending_user_id'] = $userId;
                        $_SESSION['pending_company_id'] = $companyId;
                        $_SESSION['pending_password'] = $password;
                        $_SESSION['pending_email'] = $email;
                        
                        // Redirect to checkout
                        header('Location: /checkout.php?plan=' . $selectedPlanId . '&cycle=' . $selectedCycle . '&currency=' . $selectedCurrency . '&new_signup=1');
                        exit;
                    }
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $errors[] = "Registration failed: " . $e->getMessage();
                    error_log("Registration error: " . $e->getMessage());
                }
            }
        } catch (PDOException $e) {
            $errors[] = "Database connection failed. Please try again.";
            error_log("Database error: " . $e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Account - Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <script>
        (function() {
            var saved = localStorage.getItem('theme') || 'dark';
            document.documentElement.setAttribute('data-theme', saved);
        })();
    </script>
    </head>
    <body>
        <div class="funnel-shell">
        <!-- Navigation -->
        <header class="funnel-header">
            <div class="funnel-header__inner">
                <a class="funnel-header__brand" href="/">
                    <img src="/assets/Keelance-Logo Light.svg" alt="Keelance" class="funnel-header__logo theme-logo--dark">
                    <img src="/assets/KeelanceLogo.png" alt="Keelance" class="funnel-header__logo theme-logo--light">
                </a>
                <div class="funnel-header__actions">
                    <a href="/signup-plans.php" class="btn-secondary btn-sm">← Change Plan</a>
                    <a href="/login.php" class="btn-secondary btn-sm">Sign in</a>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="funnel-main">
            <div class="page-narrow">
                <!-- Header -->
                <div class="funnel-hero">
                    <h1 class="funnel-title">Create Your Account</h1>
                    <p class="funnel-subtitle">
                        You're signing up for the <strong><?= htmlspecialchars(SubscriptionManager::getPlanName($selectedPlanId)) ?></strong> plan
                    </p>
                    <div style="margin-top: 10px; display: flex; justify-content: center;">
                        <span class="status-chip">
                            <?= $currencySymbol ?><?= number_format(SubscriptionManager::getPlanPrice($selectedPlanId, $selectedCycle), 2) ?>
                            <?= $selectedCycle === 'yearly' ? '/year' : '/month' ?>
                        </span>
                    </div>
                </div>

                <!-- Form Card -->
                <div class="card card--static" style="padding: 22px;">
                        <?php
                            $highlights = array_slice(SubscriptionManager::getPlanFeatures($selectedPlanId), 0, 2);
                        ?>

                        <?php if (!empty($highlights)): ?>
                            <div class="alert">
                                <div>
                                    <p class="section-title" style="margin: 0 0 6px;">Selected plan</p>
                                    <p style="margin: 0; font-size: 12px; color: var(--text-primary); font-weight: 600;">
                                        <?= htmlspecialchars($plan['name']) ?>
                                        · <?= $currencySymbol ?><?= number_format($displayPrice, 2) ?> <?= $displayLabel ?>
                                    </p>
                                </div>
                                <div style="margin-top: 8px; font-size: 12px; color: var(--text-secondary);">
                                    <?= htmlspecialchars(implode(' • ', $highlights)) ?>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($errors)): ?>
                            <div class="alert alert--danger">
                                <?php foreach ($errors as $error): ?>
                                    <p><?= htmlspecialchars($error) ?></p>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>

                        <form method="POST" class="form-stack" style="gap: 18px;">
                            <input type="hidden" name="billing_cycle" value="<?= htmlspecialchars($selectedCycle) ?>">
                            <!-- Personal Information -->
                            <div>
                                <h2 class="card-title">Personal Information</h2>
                                
                                <div class="form-grid-2">
                                    <div class="form-field">
                                        <label for="name" class="form-label">Full Name</label>
                                        <input type="text" id="name" name="name" required class="form-input" placeholder="John Doe" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>">
                                    </div>
                                    
                                    <div class="form-field">
                                        <label for="email" class="form-label">Email Address</label>
                                        <input type="email" id="email" name="email" required class="form-input" placeholder="john@example.com" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
                                    </div>
                                </div>

                                <div class="form-grid-2" style="margin-top: 12px;">
                                    <div class="form-field">
                                        <label for="password" class="form-label">Password</label>
                                        <input type="password" id="password" name="password" required class="form-input" placeholder="Create password">
                                        <p class="form-hint">Minimum 8 characters</p>
                                    </div>
                                    
                                    <div class="form-field">
                                        <label for="confirm_password" class="form-label">Confirm Password</label>
                                        <input type="password" id="confirm_password" name="confirm_password" required class="form-input" placeholder="Confirm password">
                                    </div>
                                </div>
                            </div>

                            <!-- Company Information -->
                            <div>
                                <h2 class="card-title">Company Information</h2>
                                
                                <div class="form-grid-2">
                                    <div class="form-field">
                                        <label for="company_name" class="form-label">Company Name</label>
                                        <input type="text" id="company_name" name="company_name" required class="form-input" placeholder="Acme Corporation" value="<?= htmlspecialchars($_POST['company_name'] ?? '') ?>">
                                    </div>
                                    
                                    <div class="form-field">
                                        <label for="company_username" class="form-label">Company Username</label>
                                        <input type="text" id="company_username" name="company_username" required pattern="[a-zA-Z0-9_-]+" minlength="3" maxlength="20" class="form-input" placeholder="acme-corp" value="<?= htmlspecialchars($_POST['company_username'] ?? '') ?>">
                                        <p class="form-hint">3-20 chars, letters/numbers/_/- only</p>
                                    </div>
                                </div>
                            </div>

                            <!-- Submit Button -->
                            <div class="row" style="justify-content: flex-end; margin-top: 10px;">
                                <a href="/signup-plans.php" class="btn-secondary">Cancel</a>
                                <button type="submit" class="btn-primary">Create Account</button>
                            </div>
                        </form>
                </div>
            </div>
        </main>

        <!-- Global Footer -->
        <?php include __DIR__ . '/footer.php'; ?>
    </div>
</body>
</html>
