<?php
require_once __DIR__ . '/db/config.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $company_name = $_POST['company_name'] ?? '';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';

    if (empty($company_name) || empty($email) || empty($password)) {
        $error_message = 'All fields are required.';
    } else {
        try {
            $pdo = db();

            // Check if email already exists
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $error_message = 'A user with this email already exists.';
            } else {
                // Start transaction
                $pdo->beginTransaction();

                // 1. Create company
                $stmt = $pdo->prepare("INSERT INTO companies (name) VALUES (?)");
                $stmt->execute([$company_name]);
                $company_id = $pdo->lastInsertId();

                // 2. Create admin user
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("INSERT INTO users (company_id, email, password, role) VALUES (?, ?, ?, 'admin')");
                $stmt->execute([$company_id, $email, $hashed_password]);
                $user_id = $pdo->lastInsertId();

                // 3. Create a corresponding employee record for the admin user
                // For simplicity, we'll use the email prefix as first/last name
                $email_parts = explode('@', $email);
                $first_name = ucfirst($email_parts[0]);
                $last_name = 'Admin';

                $stmt = $pdo->prepare("INSERT INTO employees (user_id, company_id, first_name, last_name, position) VALUES (?, ?, ?, ?, 'Administrator')");
                $stmt->execute([$user_id, $company_id, $first_name, $last_name]);

                // Commit transaction
                $pdo->commit();

                header('Location: /login.php?registration=success');
                exit;
            }
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error_message = "Registration failed: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - GPTPayroll</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center min-h-screen">

    <div class="w-full max-w-md bg-white p-8 rounded-lg shadow-md">
        <div class="text-center mb-8">
            <a href="/" class="text-3xl font-bold bg-clip-text text-transparent" style="background: linear-gradient(45deg, #10B981, #F59E0B, #EF4444);">GPTPayroll</a>
            <h2 class="mt-2 text-2xl font-bold text-gray-800">Create Your Company Account</h2>
        </div>

        <?php if ($error_message): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                <span class="block sm:inline"><?= htmlspecialchars($error_message) ?></span>
            </div>
        <?php endif; ?>

        <form action="/register.php" method="POST">
            <div class="mb-4">
                <label for="company_name" class="block text-gray-700 text-sm font-bold mb-2">Company Name</label>
                <input type="text" id="company_name" name="company_name" required class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline">
            </div>
            <div class="mb-4">
                <label for="email" class="block text-gray-700 text-sm font-bold mb-2">Your Email</label>
                <input type="email" id="email" name="email" required class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline">
            </div>
            <div class="mb-6">
                <label for="password" class="block text-gray-700 text-sm font-bold mb-2">Password</label>
                <input type="password" id="password" name="password" required class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 mb-3 leading-tight focus:outline-none focus:shadow-outline">
            </div>
            <div class="flex items-center justify-between">
                <button type="submit" class="w-full bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">
                    Create Account
                </button>
            </div>
        </form>
        <p class="text-center text-gray-500 text-xs mt-6">
            Already have an account? <a href="/login.php" class="text-green-500 hover:text-green-700">Log in here</a>.
        </p>
    </div>

</body>
</html>
