<?php
session_start();
require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/debug_logger.php';

// Debug: Log request method
debug_log("Request method: " . $_SERVER['REQUEST_METHOD']);
debug_log("POST data: " . json_encode($_POST));

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

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && (!isset($_POST['action']) || $_POST['action'] !== 'new_company')) {
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    
    debug_log("Login attempt for email: " . $email);
    
    if (empty($email) || empty($password)) {
        $errors[] = 'Email and password are required';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address';
    } else {
        // Validate user credentials
        $pdo = getPDO();
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        debug_log("User found: " . ($user ? 'yes' : 'no'));
        
        if ($user && password_verify($password, $user['password_hash'] ?? '')) {
            debug_log("Password verified successfully");
            
            // Create session token for AuthManager
            $sessionToken = bin2hex(random_bytes(32));
            $expiresAt = date('Y-m-d H:i:s', strtotime('+30 days'));
            
            debug_log("Creating session token: " . substr($sessionToken, 0, 8) . "...");
            
            // Store session token in database
            try {
                $stmt = $pdo->prepare("INSERT INTO user_sessions (user_id, session_token, expires_at, created_at) VALUES (?, ?, ?, NOW())");
                $result = $stmt->execute([$user['id'], $sessionToken, $expiresAt]);
                debug_log("Session token stored: " . ($result ? 'yes' : 'no'));
            } catch (Exception $e) {
                debug_log("Session token insert error: " . $e->getMessage());
            }
            
            // Set auth token cookie
            setcookie('auth_token', $sessionToken, [
                'expires' => strtotime('+30 days'),
                'path' => '/',
                'httponly' => true,
                'samesite' => 'Strict'
            ]);
            
            debug_log("Auth token cookie set");
            
            // Also set session for backward compatibility
            $_SESSION['user_id'] = $user['id'];
            
            // Get user's company
            $stmt = $pdo->prepare("SELECT * FROM companies WHERE id = ?");
            $stmt->execute([$user['company_id']]);
            $company = $stmt->fetch();
            
            debug_log("Company found: " . ($company ? 'yes' : 'no'));
            
            if ($company) {
                $_SESSION['current_company_id'] = $company['id'];
                $_SESSION['current_company'] = [
                    'id' => $company['id'],
                    'name' => $company['name'],
                    'username' => $company['username']
                ];
                
                // Debug: Log the redirect
                debug_log("Login successful. Redirecting to: /index.php?workspace=" . $company['username']);
                
                // Redirect to dashboard with workspace parameter
                if (!empty($company['username'])) {
                    header('Location: /index.php?workspace=' . urlencode($company['username']));
                } else {
                    header('Location: /index.php');
                }
                exit;
            } else {
                debug_log("Company not found for user_id: " . $user['id'] . ", company_id: " . $user['company_id']);
                $errors[] = 'Company not found';
            }
        } else {
            debug_log("Login failed for email: " . $email);
            $errors[] = 'Invalid email or password';
        }
    }
    
    // Log any errors
    if (!empty($errors)) {
        debug_log("Login errors: " . implode(', ', $errors));
    }
}

// Handle new company creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'new_company') {
    $companyName = $_POST['company_name'] ?? '';
    $planId = $_POST['plan_id'] ?? 2;
    
    if (empty($companyName)) {
        $errors[] = 'Company name is required';
    } else {
        try {
            $pdo = getPDO();
            
            // Create new company (without is_active column)
            $stmt = $pdo->prepare("INSERT INTO companies (name, subdomain, plan_id, subscription_status, created_at, updated_at) VALUES (?, ?, ?, 'trial', NOW(), NOW())");
            $subdomain = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $companyName)) . uniqid();
            $stmt->execute([$companyName, $subdomain, $planId]);
            $newCompanyId = $pdo->lastInsertId();
            
            // Create subscription with required fields
            $trialEndsAt = date('Y-m-d H:i:s', strtotime('+14 days'));
            $periodEnd = date('Y-m-d H:i:s', strtotime('+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, updated_at) VALUES (?, ?, 'trial', 'monthly', NOW(), ?, ?, NOW(), NOW())");
            $stmt->execute([$newCompanyId, $planId, $periodEnd, $trialEndsAt]);
            
            $_SESSION['success'] = 'Company created successfully!';
            
            // Switch to new company
            $_SESSION['current_company_id'] = $newCompanyId;
            
            header('Location: /index.php?welcome_company=1');
            exit;
        } catch (Exception $e) {
            $errors[] = 'Failed to create company: ' . $e->getMessage();
        }
    }
}

// Handle registration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'register') {
    $userData = [
        'name' => $_POST['name'] ?? '',
        'email' => $_POST['email'] ?? '',
        'password' => $_POST['password'] ?? '',
        'confirm_password' => $_POST['confirm_password'] ?? ''
    ];
    
    $companyData = [
        'name' => $_POST['company_name'] ?? '',
        'username' => $_POST['company_username'] ?? '',
        'plan_id' => $_POST['plan_id'] ?? 2 // Default to Professional plan
    ];
    
    // Validation
    if (empty($userData['name']) || empty($userData['email']) || empty($userData['password']) || empty($companyData['name']) || empty($companyData['username'])) {
        $errors[] = 'All fields are required';
    } elseif (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address';
    } elseif (strlen($userData['password']) < 8) {
        $errors[] = 'Password must be at least 8 characters long';
    } elseif ($userData['password'] !== $userData['confirm_password']) {
        $errors[] = 'Passwords do not match';
    } elseif (!preg_match('/^[a-zA-Z0-9_-]+$/', $companyData['username'])) {
        $errors[] = 'Company username can only contain letters, numbers, underscores, and hyphens';
    } elseif (strlen($companyData['username']) < 3) {
        $errors[] = 'Company username must be at least 3 characters long';
    } elseif (strlen($companyData['username']) > 20) {
        $errors[] = 'Company username must be less than 20 characters';
    } else {
        // Check if username is already taken
        try {
            $pdo = getPDO();
            $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
            $stmt->execute([$companyData['username']]);
            if ($stmt->fetch()) {
                $errors[] = 'Company username is already taken';
            }
        } catch (Exception $e) {
            // Username column doesn't exist yet, skip check
        }
        try {
            $result = AuthManager::register($userData, $companyData);
            
            if ($result['success']) {
                // Log the user in
                AuthManager::login($userData['email'], $userData['password']);
                
                // Redirect to new company subdomain
                $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
                $host = $result['subdomain'] . '.' . $_SERVER['HTTP_HOST'];
                header("Location: {$protocol}{$host}/index.php?welcome=1");
                exit;
            }
        } catch (Exception $e) {
            $errors[] = 'Registration failed: ' . $e->getMessage();
        }
    }
}

// Handle new company action
if (isset($_GET['action']) && $_GET['action'] === 'new_company') {
    // If user is logged in, show new company form with pricing plans
    if (AuthManager::isAuthenticated()) {
        $showNewCompanyForm = true;
        $user = AuthManager::getCurrentUser();
    } else {
        // If not logged in, redirect to login with new company flag
        header('Location: /login.php?new_company=1');
        exit;
    }
} else {
    $showNewCompanyForm = false;
}

// Handle new company flag in login page
if (isset($_GET['new_company']) && $_GET['new_company'] === '1') {
    $showNewCompanyForm = true;
}

// Get subscription plans for registration
$subscriptionPlans = [];
try {
    $pdo = getPDO();
    $stmt = $pdo->query("SELECT * FROM subscription_plans WHERE is_active = 1 ORDER BY price_monthly ASC");
    $subscriptionPlans = $stmt->fetchAll();
} catch (PDOException $e) {
    // Table doesn't exist, create default plans
    $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'])
        ]
    ];
} // Added closing bracket here
?>
<!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>Login · 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>
	<style>
		@keyframes auth-fade-up {
			0% {
				opacity: 0;
				transform: translateY(8px) scale(0.98);
			}
			100% {
				opacity: 1;
				transform: translateY(0) scale(1);
			}
		}
		
		@keyframes auth-fade-in {
			0% {
				opacity: 0;
				transform: translateY(4px);
			}
			100% {
				opacity: 1;
				transform: translateY(0);
			}
		}
		
		.auth-card-animate {
			animation: auth-fade-up 0.45s ease-out;
		}
		
		.auth-logo-animate {
			animation: auth-fade-in 0.6s ease-out;
		}
	</style>
</head>
<body>
<div class="funnel-shell">
	<main class="funnel-main funnel-main--center">
		<div class="funnel-card auth-card-animate">
			<!-- Logo -->
			<div style="display: flex; justify-content: center; margin-bottom: 14px;">
				<img src="/assets/Keelance-Logo Light.svg" alt="Keelance" class="auth-logo-animate theme-logo--dark" style="height: 34px; width: auto;">
				<img src="/assets/KeelanceLogo.png" alt="Keelance" class="auth-logo-animate theme-logo--light" style="height: 34px; width: auto;">
			</div>

			<!-- Login Form -->
			<?php if (!$showNewCompanyForm): ?>
			<div class="card card--static auth-card">
				<div style="margin-bottom: 10px;">
					<h2 class="card-title" style="margin-top: 0;">Sign in to Keelance</h2>
					<p class="card-subtitle">Access your proposals, contracts, invoices, and more.</p>
				</div>
				
				<?php if (!empty($errors)): ?>
					<div class="alert alert--danger">
						<?php foreach ($errors as $error): ?>
							<p><?= htmlspecialchars($error) ?></p>
						<?php endforeach; ?>
					</div>
				<?php endif; ?>

				<form id="loginForm" class="form-stack" method="POST">
					<div class="form-field">
						<label for="email" class="form-label">Email</label>
						<input id="email" name="email" type="email" autocomplete="email" required class="form-input" placeholder="name@example.com" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
					</div>
					
					<div class="form-field">
						<label for="password" class="form-label">Password</label>
						<input id="password" name="password" type="password" autocomplete="current-password" required class="form-input" placeholder="Enter your password">
					</div>
					
					<div class="row-between">
						<label class="row" style="gap: 8px; font-size: 12px; color: var(--text-secondary);">
							<input type="checkbox" class="form-checkbox">
							<span>Remember me</span>
						</label>
						<a href="/forgot-password.php" class="btn-secondary btn-sm">Forgot password?</a>
					</div>
					
					<button type="submit" class="btn-primary btn-block">
						Sign in
					</button>
				</form>
				
				<div style="text-align: center; margin-top: 10px; font-size: 12px; color: var(--text-tertiary);">
					Don't have an account? 
					<a href="/signup-plans.php" class="btn-secondary btn-sm">Sign up</a>
				</div>
			</div>
			<?php endif; ?>

			<!-- Registration Form -->
			<div id="registerForm" class="card card--static auth-card" style="display: none;">
				<input type="hidden" name="action" value="register">
				
				<?php if (!empty($errors)): ?>
					<div class="alert alert--danger">
						<?php foreach ($errors as $error): ?>
							<p><?= htmlspecialchars($error) ?></p>
						<?php endforeach; ?>
					</div>
				<?php endif; ?>

				<form class="form-stack" method="POST">
					<div>
						<h2 class="card-title" style="margin-top: 0;">Create your Keelance account</h2>
						<p class="card-subtitle">Set up your workspace and invite your team later.</p>
					</div>
					<div class="form-field">
						<label for="reg_name" class="form-label">Name</label>
						<input id="reg_name" name="name" type="text" required class="form-input" placeholder="Your name" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>">
					</div>
				
					<div class="form-field">
						<label for="reg_email" class="form-label">Email</label>
						<input id="reg_email" name="email" type="email" required class="form-input" placeholder="name@example.com" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
					</div>
				
					<div class="form-field">
						<label for="company_name" class="form-label">Company name</label>
						<input id="company_name" name="company_name" type="text" required class="form-input" placeholder="Your company" value="<?= htmlspecialchars($_POST['company_name'] ?? '') ?>">
					</div>
				
					<div class="form-field">
						<label for="company_username" class="form-label">Company username</label>
						<input id="company_username" name="company_username" type="text" required pattern="[a-zA-Z0-9_-]+" minlength="3" maxlength="20" class="form-input" placeholder="company-username" value="<?= htmlspecialchars($_POST['company_username'] ?? '') ?>">
						<p class="form-hint">3-20 characters, letters, numbers, _ and - only</p>
					</div>
				
					<div class="form-field">
						<label for="reg_password" class="form-label">Password</label>
						<input id="reg_password" name="password" type="password" required class="form-input" placeholder="Create password">
					</div>
				
					<div class="form-field">
						<label for="confirm_password" class="form-label">Confirm password</label>
						<input id="confirm_password" name="confirm_password" type="password" required class="form-input" placeholder="Confirm password">
					</div>
				
					<!-- Plan Selection -->
					<div>
						<label class="form-label">Choose plan</label>
						<div class="form-stack">
							<?php foreach ($subscriptionPlans as $plan): ?>
								<label style="display: block; cursor: pointer;">
									<input type="radio" name="plan_id" value="<?= $plan['id'] ?>" <?= $plan['name'] === 'Professional' ? 'checked' : ''; ?> style="display: none;">
									<div class="billing-plan-card">
										<div class="billing-plan-name" style="font-size: 12px; font-weight: 600; color: var(--text-primary);"><?= htmlspecialchars($plan['name']) ?></div>
										<div class="billing-plan-price" style="font-size: 11px; color: var(--text-tertiary);">$<?= number_format($plan['price_monthly'], 0) ?>/month</div>
									</div>
								</label>
							<?php endforeach; ?>
						</div>
					</div>
				
					<button type="submit" class="btn-primary btn-block">
						Create account
					</button>
				
					<div style="text-align: center; font-size: 12px; color: var(--text-tertiary);">
						Already have an account? 
						<a href="#" onclick="showLogin()" class="btn-secondary btn-sm">Sign in</a>
					</div>
				</form>
			</div>

			<!-- New Company Form -->
			<?php if ($showNewCompanyForm): ?>
			<div class="card card--static auth-card">
				<div style="margin-bottom: 10px;">
					<h2 class="card-title" style="margin-top: 0;">Create a new workspace</h2>
					<p class="card-subtitle">Spin up an additional workspace under your account.</p>
				</div>
					<?php if (!empty($errors)): ?>
						<div class="alert alert--danger">
							<?php foreach ($errors as $error): ?>
								<p><?= htmlspecialchars($error) ?></p>
							<?php endforeach; ?>
						</div>
					<?php endif; ?>

					<form id="newCompanyForm" class="form-stack" method="POST">
						<input type="hidden" name="action" value="new_company">
						
						<div class="form-field">
							<label for="company_name" class="form-label">Company name</label>
							<input id="company_name" name="company_name" type="text" required class="form-input" placeholder="Your company name" value="<?= htmlspecialchars($_POST['company_name'] ?? '') ?>">
						</div>
					
						<!-- Plan Selection -->
						<div>
							<label class="form-label">Choose plan</label>
							<div class="form-stack">
								<?php foreach ($subscriptionPlans as $plan): ?>
									<label style="display: block; cursor: pointer;">
										<input type="radio" name="plan_id" value="<?= $plan['id'] ?>" <?= $plan['name'] === 'Professional' ? 'checked' : ''; ?> style="display: none;">
										<div class="billing-plan-card">
											<div class="billing-plan-name" style="font-size: 12px; font-weight: 600; color: var(--text-primary);"><?= htmlspecialchars($plan['name']) ?></div>
											<div class="billing-plan-price" style="font-size: 11px; color: var(--text-tertiary);">$<?= number_format($plan['price_monthly'], 0) ?>/month</div>
										</div>
									</label>
								<?php endforeach; ?>
							</div>
						</div>
					
						<button type="submit" class="btn-primary btn-block">
							Create workspace
						</button>
					</form>
			</div>
			<?php endif; ?>
		</div>
	</main>

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

<script>
	function showRegister() {
		var loginForm = document.getElementById('loginForm');
		var registerForm = document.getElementById('registerForm');
		if (loginForm && loginForm.parentElement) {
			loginForm.parentElement.style.display = 'none';
		}
		if (registerForm) {
			registerForm.style.display = 'block';
		}
	}

	function showLogin() {
		var loginForm = document.getElementById('loginForm');
		var registerForm = document.getElementById('registerForm');
		if (registerForm) {
			registerForm.style.display = 'none';
		}
		if (loginForm && loginForm.parentElement) {
			loginForm.parentElement.style.display = 'block';
		}
	}
</script>

</body>
</html>
