<?php
/**
 * Primary Client / Account Registration Page
 * Location: public_html/register.php
 */

require_once __DIR__ . '/connections/connect.php';
require_once __DIR__ . '/includes/functions.php';

$errors = [];
$success_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $full_name = sanitize_input($_POST['full_name'] ?? '');
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
    $company_name = sanitize_input($_POST['company_name'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $terms = isset($_POST['terms']);

    if (empty($full_name)) $errors[] = "Full Name is required.";
    if (!$email) $errors[] = "Please enter a valid email address.";
    if (empty($company_name)) $errors[] = "Company Name is required.";
    if (strlen($password) < 6) $errors[] = "Password must be at least 6 characters long.";
    if ($password !== $confirm_password) $errors[] = "Password confirmation does not match.";
    if (!$terms) $errors[] = "You must agree to the Terms & Conditions.";

    if (empty($errors)) {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            $errors[] = "An account with this email address already exists.";
        } else {
            try {
                $pdo->beginTransaction();

                // 1. Create Account
                $account_id = 'acc_' . bin2hex(random_bytes(6));
                $stmt_acc = $pdo->prepare("INSERT INTO accounts (id, company_name) VALUES (?, ?)");
                $stmt_acc->execute([$account_id, $company_name]);

                // 2. Create User (Unverified)
                $user_id = 'usr_' . bin2hex(random_bytes(6));
                $name_parts = explode(' ', $full_name, 2);
                $first_name = $name_parts[0];
                $last_name = $name_parts[1] ?? '';
                $password_hash = password_hash($password, PASSWORD_DEFAULT);

                $stmt_usr = $pdo->prepare("INSERT INTO users (id, account_id, email, password_hash, first_name, last_name, role, is_verified) VALUES (?, ?, ?, ?, ?, ?, 'PRIMARY_ADMIN', 0)");
                $stmt_usr->execute([$user_id, $account_id, $email, $password_hash, $first_name, $last_name]);

                // 3. Create Verification Token
                $token = generate_token(32);
                $expires_at = date('Y-m-d H:i:s', strtotime('+24 hours'));
                $stmt_ver = $pdo->prepare("INSERT INTO email_verifications (id, user_id, token, expires_at) VALUES (?, ?, ?, ?)");
                $stmt_ver->execute(['ver_' . bin2hex(random_bytes(6)), $user_id, $token, $expires_at]);

                $pdo->commit();

                $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
                $host = $_SERVER['HTTP_HOST'];
                $verification_link = "{$protocol}://{$host}/public_html/verify_email.php?token={$token}";

                send_verification_email($email, $first_name, $verification_link);

                $success_msg = "Account created successfully! We have sent a verification link to <strong>" . htmlspecialchars($email) . "</strong>. Please check your inbox or <code>public_html/mail_debug.log</code> in local XAMPP to verify.";
            } catch (Exception $e) {
                $pdo->rollBack();
                $errors[] = "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>Create an Account - MiBuildqc</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
        body { font-family: 'Plus Jakarta Sans', sans-serif; }
    </style>
</head>
<body class="bg-slate-200 min-h-screen flex items-center justify-center p-4">

    <div class="bg-white rounded-[24px] max-w-[420px] w-full p-8 shadow-xl border border-slate-100 space-y-6">
        
        <div class="bg-slate-900 rounded-xl py-3 px-6 text-center shadow-xs">
            <span class="text-3xl font-extrabold text-white tracking-tight">
                MiBuild<span class="text-indigo-300">qc</span>
            </span>
        </div>

        <h1 class="text-2xl font-bold text-center text-slate-500">Create an Account</h1>

        <?php if (!empty($errors)): ?>
            <div class="p-3.5 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-xs space-y-1">
                <?php foreach ($errors as $err): ?>
                    <p>&bull; <?php echo $err; ?></p>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if ($success_msg): ?>
            <div class="p-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-900 text-xs space-y-2">
                <p><?php echo $success_msg; ?></p>
                <div class="pt-2 text-center">
                    <a href="login.php" class="inline-block px-4 py-2 bg-emerald-700 text-white font-bold rounded-lg hover:bg-emerald-800">Go to Login Page</a>
                </div>
            </div>
        <?php else: ?>

        <form action="register.php" method="POST" class="space-y-4">
            <div>
                <label class="block text-xs font-semibold text-slate-500 mb-1">Full Name</label>
                <input type="text" name="full_name" required value="<?php echo htmlspecialchars($_POST['full_name'] ?? ''); ?>" placeholder="John Doe" class="w-full px-3.5 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:border-[#635BFF] focus:ring-1 focus:ring-[#635BFF]">
            </div>

            <div>
                <label class="block text-xs font-semibold text-slate-500 mb-1">Email Address</label>
                <input type="email" name="email" required value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" placeholder="john@example.com" class="w-full px-3.5 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:border-[#635BFF] focus:ring-1 focus:ring-[#635BFF]">
            </div>

            <div>
                <label class="block text-xs font-semibold text-slate-500 mb-1">Company Name</label>
                <input type="text" name="company_name" required value="<?php echo htmlspecialchars($_POST['company_name'] ?? ''); ?>" placeholder="MiBuild QC" class="w-full px-3.5 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:border-[#635BFF] focus:ring-1 focus:ring-[#635BFF]">
            </div>

            <div class="grid grid-cols-2 gap-3">
                <div>
                    <label class="block text-xs font-semibold text-slate-500 mb-1">Password</label>
                    <input type="password" name="password" required class="w-full px-3.5 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:border-[#635BFF] focus:ring-1 focus:ring-[#635BFF]">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-500 mb-1">Confirm Password</label>
                    <input type="password" name="confirm_password" required class="w-full px-3.5 py-2.5 rounded-xl border border-slate-200 text-sm focus:outline-none focus:border-[#635BFF] focus:ring-1 focus:ring-[#635BFF]">
                </div>
            </div>

            <div class="flex items-center gap-2 pt-1">
                <input type="checkbox" id="terms" name="terms" required class="w-4 h-4 rounded border-slate-300 text-[#635BFF] focus:ring-[#635BFF]">
                <label for="terms" class="text-xs text-slate-600">
                    I agree to the <a href="#" class="underline font-medium text-slate-900">Terms & Conditions</a>
                </label>
            </div>

            <button type="submit" class="w-full py-3 px-4 rounded-xl bg-[#6114ff] hover:bg-indigo-500 text-white text-xs font-bold uppercase tracking-wider transition-all shadow-md mt-2">
                REGISTER NOW
            </button>
        </form>

        <?php endif; ?>

        <div class="text-center text-xs text-slate-500 pt-2">
            Already have an account? <a href="login.php" class="font-bold text-slate-800 hover:underline">Login</a>
        </div>

    </div>

</body>
</html>