<?php
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/Permissions/PermissionManager.php';
require_once __DIR__ . '/../src/SuperAdmin/PlatformSettings.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';

// Require authentication
AuthManager::requireAuth();

// 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);

$errors = [];
$success = '';

// Get subscription plans
$subscriptionPlans = [];
try {
    $pdo = getPDO();
    $stmt = $pdo->query("SELECT * FROM subscription_plans WHERE is_active = 1 ORDER BY sort_order ASC");
    $subscriptionPlans = $stmt->fetchAll();
} catch (PDOException $e) {
    // Default plans if table doesn't exist
    $subscriptionPlans = [
        [
            'id' => 1,
            'name' => 'Starter',
            'price_monthly' => 29,
            'price_yearly' => 290,
            'features' => json_encode(['Up to 5 clients', 'Up to 10 proposals/month', 'Basic support'])
        ],
        [
            'id' => 2,
            'name' => 'Professional',
            'price_monthly' => 79,
            'price_yearly' => 790,
            'features' => json_encode(['Up to 50 clients', 'Unlimited proposals', 'Priority support', 'Custom branding'])
        ],
        [
            'id' => 3,
            'name' => 'Enterprise',
            'price_monthly' => 199,
            'price_yearly' => 1990,
            'features' => json_encode(['Unlimited clients', 'Unlimited everything', '24/7 support', 'API access', 'Custom integrations'])
        ]
    ];
}

$defaultPlanId = $subscriptionPlans[1]['id'] ?? ($subscriptionPlans[0]['id'] ?? 1);
$selectedBillingCycle = $_POST['billing_cycle'] ?? $_GET['cycle'] ?? 'monthly';
$selectedBillingCycle = $selectedBillingCycle === 'yearly' ? 'yearly' : 'monthly';
$selectedPlanId = (int) ($_POST['plan_id'] ?? $_GET['plan_id'] ?? $defaultPlanId);
$planId = $selectedPlanId;

// Currency handling
$selectedCurrency = $_POST['currency'] ?? $_GET['currency'] ?? $_SESSION['currency'] ?? $_COOKIE['currency'] ?? 'USD';
if (!in_array($selectedCurrency, ['USD', 'INR'])) {
    $selectedCurrency = 'USD';
}
$_SESSION['currency'] = $selectedCurrency;
$currencySymbol = $selectedCurrency === 'INR' ? '₹' : '$';
$selectedPlanData = null;
foreach ($subscriptionPlans as $plan) {
    if ((int)$plan['id'] === $selectedPlanId) {
        $selectedPlanData = $plan;
        break;
    }
}
$selectedPlanFeatures = $selectedPlanData ? (json_decode($selectedPlanData['features'] ?? '[]', true) ?? []) : [];

// Handle workspace creation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $workspaceName = trim($_POST['workspace_name'] ?? '');
    $workspaceUsername = trim($_POST['workspace_username'] ?? '');
    
    // Validation
    if (empty($workspaceName)) {
        $errors[] = 'Workspace name is required';
    }
    
    if (empty($workspaceUsername)) {
        $errors[] = 'Workspace username is required';
    } elseif (!preg_match('/^[a-zA-Z0-9_-]+$/', $workspaceUsername)) {
        $errors[] = 'Workspace username can only contain letters, numbers, underscores, and hyphens';
    } elseif (strlen($workspaceUsername) < 3) {
        $errors[] = 'Workspace username must be at least 3 characters long';
    } elseif (strlen($workspaceUsername) > 20) {
        $errors[] = 'Workspace username must be less than 20 characters';
    } else {
        // Check if username is already taken
        $pdo = getPDO();
        $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
        $stmt->execute([$workspaceUsername]);
        if ($stmt->fetch()) {
            $errors[] = 'Workspace username is already taken';
        }
    }
    
    if (empty($errors)) {
        try {
            $user = AuthManager::getCurrentUser();
            
            // Check if this specific plan has trial
            $thisPlanHasTrial = $trialEnabled && $trialDays > 0 && 
                ($trialApplyTo === 'all' || $planId === $trialPlanId);
            
            $subscriptionStatus = $thisPlanHasTrial ? 'trial' : 'active';
            $trialEndsAt = $thisPlanHasTrial 
                ? date('Y-m-d H:i:s', strtotime("+{$trialDays} days"))
                : null;
            $periodEnd = $thisPlanHasTrial
                ? $trialEndsAt
                : ($selectedBillingCycle === 'yearly'
                    ? date('Y-m-d H:i:s', strtotime('+1 year'))
                    : date('Y-m-d H:i:s', strtotime('+1 month')));
            
            // Create new workspace/company with preferred currency
            $stmt = $pdo->prepare("INSERT INTO companies (name, username, subdomain, plan_id, subscription_status, preferred_currency, owner_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
            $subdomain = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $workspaceName)) . uniqid();
            $stmt->execute([$workspaceName, $workspaceUsername, $subdomain, $planId, $subscriptionStatus, $selectedCurrency, $user['id']]);
            $newCompanyId = $pdo->lastInsertId();
            
            // Create subscription reflecting billing cycle
            $stmt = $pdo->prepare("INSERT INTO subscriptions (company_id, plan_id, status, billing_cycle, current_period_start, current_period_end, trial_ends_at, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), ?, ?, NOW(), NOW())");
            $stmt->execute([$newCompanyId, $planId, $subscriptionStatus, $selectedBillingCycle, $periodEnd, $trialEndsAt]);
            
            // Update company subscription metadata
            $stmt = $pdo->prepare("UPDATE companies SET plan_id = ?, subscription_status = ?, billing_cycle = ?, subscription_expires_at = ? WHERE id = ?");
            $stmt->execute([$planId, $subscriptionStatus, $selectedBillingCycle, $periodEnd, $newCompanyId]);
            
            // Ensure mapping table exists
            $pdo->exec("CREATE TABLE IF NOT EXISTS user_company_access (
                id INT PRIMARY KEY AUTO_INCREMENT,
                user_id INT NOT NULL,
                company_id INT NOT NULL,
                role ENUM('owner','admin','member') DEFAULT 'member',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY unique_user_company (user_id, company_id)
            )");
            
            // Determine valid role to store
            $roleValue = 'owner';
            try {
                $columnStmt = $pdo->query("SHOW COLUMNS FROM user_company_access LIKE 'role'");
                $column = $columnStmt ? $columnStmt->fetch(PDO::FETCH_ASSOC) : null;
                if ($column && isset($column['Type']) && stripos($column['Type'], 'enum(') === 0) {
                    $enumOptions = array_map(static function ($value) {
                        return trim($value, "'\" ");
                    }, explode(',', substr($column['Type'], 5, -1)));
                    if (!in_array('owner', $enumOptions, true)) {
                        $roleValue = $enumOptions[0] ?? 'member';
                    }
                }
            } catch (PDOException $ignored) {
                // If inspection fails, fall back to default roleValue
            }

            // Grant user access/ownership to the new workspace
            $stmt = $pdo->prepare("INSERT INTO user_company_access (user_id, company_id, role, created_at) VALUES (?, ?, ?, NOW())");
            $stmt->execute([$user['id'], $newCompanyId, $roleValue]);
            
            // Set owner and create default roles using PermissionManager
            PermissionManager::addOwnerAsMember((int)$newCompanyId, (int)$user['id']);
            PermissionManager::createDefaultRoles((int)$newCompanyId);
            
            // Create workspace folder
            $workspaceFolder = __DIR__ . '/../storage/companies/' . $newCompanyId;
            if (!is_dir($workspaceFolder)) {
                mkdir($workspaceFolder, 0755, true);
            }
            
            // Switch to new workspace
            $_SESSION['current_company_id'] = $newCompanyId;
            $_SESSION['current_company'] = [
                'id' => $newCompanyId,
                'name' => $workspaceName,
                'username' => $workspaceUsername,
                'subdomain' => $subdomain
            ];
            
            header('Location: /index.php?workspace=' . $workspaceUsername . '&welcome=1');
            exit;
            
        } catch (Exception $e) {
            $errors[] = 'Failed to create workspace: ' . $e->getMessage();
        }
    }
}

$user = AuthManager::getCurrentUser();
?>
<!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 New Workspace - 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 class="app-shell create-workspace-page">
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('', 'dark'); ?>

<div class="app-shell__content">
    <div class="main-container">
        <?php
        require_once __DIR__ . '/components/headers/page-header.php';
        renderPageHeader(
            breadcrumbs: [
                ['label' => 'Home', 'url' => '/index.php', 'icon' => 'M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6'],
            ],
            currentPage: 'Create workspace',
            actions: [],
            workspaceQuery: ''
        );
        ?>

        <main>
            <div class="dash-container">
                <div class="dash-section">
                    <div class="funnel-hero" style="margin-bottom: 0;">
                        <h1 class="funnel-title">Create New Workspace</h1>
                        <p class="funnel-subtitle">Set up a new workspace for your business or project.</p>
                    </div>
                </div>

                <?php if ($selectedPlanData): ?>
                    <?php
                        $planMonthly = (float) ($selectedPlanData['price_monthly'] ?? 0);
                        $planYearly = (float) ($selectedPlanData['price_yearly'] ?? 0);
                        if ($selectedCurrency === 'INR') {
                            $planMonthly = (float) ($selectedPlanData['price_monthly_inr'] ?? ($planMonthly * 83));
                            $planYearly = (float) ($selectedPlanData['price_yearly_inr'] ?? ($planYearly * 83));
                        }
                        $displayAmount = $selectedBillingCycle === 'yearly' ? $planYearly : $planMonthly;
                        $displaySuffix = $selectedBillingCycle === 'yearly' ? '/year' : '/month';
                    ?>
                    <div class="dash-section">
                        <div class="card">
                            <div class="row-between" style="align-items: flex-start;">
                                <div>
                                    <p class="section-title" style="margin: 0 0 6px;">Selected plan</p>
                                    <p class="card-title" style="margin: 0;"><?= h($selectedPlanData['name']) ?></p>
                                    <p class="card-subtitle" style="margin: 6px 0 0;"><?= $currencySymbol ?><?= number_format($displayAmount, 0) ?><?= $displaySuffix ?></p>
                                </div>
                                <?php if (!empty($selectedPlanFeatures)): ?>
                                    <div style="text-align: right;">
                                        <p class="section-title" style="margin: 0 0 6px;">Key features</p>
                                        <p class="card-subtitle" style="margin: 0;"><?= h(implode(' • ', array_slice($selectedPlanFeatures, 0, 3))) ?></p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>

                <div class="dash-section">
                    <div class="card card--static" style="padding: 22px;">
                        <?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;">
                            <div>
                                <h2 class="card-title" style="margin-top: 0;">Workspace details</h2>
                                <p class="card-subtitle">Pick a name and a username for the new workspace.</p>
                            </div>

                            <div class="form-grid-2">
                                <div class="form-field">
                                    <label for="workspace_name" class="form-label">Workspace Name</label>
                                    <input type="text" id="workspace_name" name="workspace_name" required class="form-input" placeholder="My Business Workspace" value="<?= htmlspecialchars($_POST['workspace_name'] ?? '') ?>">
                                    <p class="form-hint">The display name for your workspace</p>
                                </div>

                                <div class="form-field">
                                    <label for="workspace_username" class="form-label">Workspace Username</label>
                                    <input type="text" id="workspace_username" name="workspace_username" required pattern="[a-zA-Z0-9_-]+" minlength="3" maxlength="20" class="form-input" placeholder="my-business" value="<?= htmlspecialchars($_POST['workspace_username'] ?? '') ?>">
                                    <p class="form-hint">3-20 chars, letters/numbers/_/- only</p>
                                </div>
                            </div>

                            <input type="hidden" name="plan_id" value="<?= (int) $selectedPlanId ?>">
                            <input type="hidden" name="billing_cycle" value="<?= htmlspecialchars($selectedBillingCycle) ?>">
                            <input type="hidden" name="currency" value="<?= htmlspecialchars($selectedCurrency) ?>">

                            <div class="row" style="justify-content: flex-end;">
                                <a href="/workspace-plans.php" class="btn-secondary">Back</a>
                                <button type="submit" class="btn-primary">Create Workspace</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<?php include __DIR__ . '/footer.php'; ?>

</body>
</html>
