<?php
require_once __DIR__ . '/../app/includes/auth.php';
header('X-Frame-Options: SAMEORIGIN');
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header("Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; script-src 'self' https://cdn.jsdelivr.net; font-src 'self' data: https://cdn.jsdelivr.net;");

if (current_user()) {
    redirect('/dashboard.php');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $name = trim((string)post('name'));
    $email = trim((string)post('email'));
    $mobile = trim((string)post('mobile_number'));
    $company = trim((string)post('company_name'));
    $password = (string)post('password');
    $confirm = (string)post('confirm_password');

    if (!$name || !$email || !$mobile || !$password) {
        flash('error', 'All fields except Company Name are required.');
        redirect('/register.php');
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        flash('error', 'Invalid email address format.');
        redirect('/register.php');
    }
    if ($password !== $confirm) {
        flash('error', 'Passwords do not match.');
        redirect('/register.php');
    }
    if (strlen($password) < 6) {
        flash('error', 'Password must be at least 6 characters.');
        redirect('/register.php');
    }

    $stmt = db()->prepare('SELECT id FROM users WHERE email = ?');
    $stmt->execute([$email]);
    if ($stmt->fetchColumn()) {
        flash('error', 'Email is already registered.');
        redirect('/register.php');
    }

    $hash = password_hash($password, PASSWORD_DEFAULT);
    
    // Generate 6-digit OTP
    $otp = str_pad((string)random_int(100000, 999999), 6, '0', STR_PAD_LEFT);
    $payload = json_encode([
        'name' => $name,
        'mobile_number' => $mobile,
        'company_name' => $company,
        'password_hash' => $hash
    ]);
    
    $expires = date('Y-m-d H:i:s', strtotime('+10 minutes'));

    $stmt = db()->prepare('REPLACE INTO email_verifications (email, otp, payload, expires_at) VALUES (?, ?, ?, ?)');
    $stmt->execute([$email, $otp, $payload, $expires]);

    // Simulated Email Send
    log_activity('otp.sent', "OTP $otp sent to $email for registration");
    $_SESSION['verification_email'] = $email;
    
    flash('success', "Your verification code is: <strong>$otp</strong>. (Simulated Email Content: This code will expire in 10 minutes.)");
    redirect('/verify_otp.php');
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Register Account - <?= APP_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="<?= APP_BASE ?>/assets/css/app.css?v=<?= time() ?>" rel="stylesheet">
</head>
<body class="login-page">
    <div class="login-card" style="max-width: 450px;">
        <div class="login-logo">F</div>
        <h1>Register Account</h1>
        <p>Create a free account to get started.</p>
        <?php if ($msg = flash('error')): ?><div class="alert alert-danger"><?= e($msg) ?></div><?php endif; ?>
        <form method="post" novalidate>
            <?= csrf_field() ?>
            <label class="form-label">Full Name</label>
            <input class="form-control mb-3" type="text" name="name" required>
            
            <label class="form-label">Email Address</label>
            <input class="form-control mb-3" type="email" name="email" autocomplete="username" required>
            
            <label class="form-label">Mobile Number</label>
            <input class="form-control mb-3" type="text" name="mobile_number" required>
            
            <label class="form-label">Company Name <span class="text-muted">(Optional)</span></label>
            <input class="form-control mb-3" type="text" name="company_name">
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Password</label>
                    <input class="form-control" type="password" name="password" autocomplete="new-password" required>
                </div>
                <div class="col-md-6 mb-4">
                    <label class="form-label">Confirm Password</label>
                    <input class="form-control" type="password" name="confirm_password" autocomplete="new-password" required>
                </div>
            </div>

            <button class="btn btn-primary w-100 mb-3" type="submit"><i class="bi bi-person-plus me-1"></i>Register Account</button>
            <div class="text-center text-muted" style="font-size:0.9rem;">
                Already have an account? <a href="<?= APP_BASE ?>/login.php" class="text-decoration-none fw-bold">Login</a>
            </div>
        </form>
    </div>
</body>
</html>
