<?php
declare(strict_types=1);

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='register.html';</script></body></html>";
    exit;
}

$pdo->exec(
    'CREATE TABLE IF NOT EXISTS users (
        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(100) NOT NULL,
        email VARCHAR(255) NOT NULL UNIQUE,
        password_hash VARCHAR(255) NOT NULL,
        role ENUM("Seller","Buyer","Admin") NOT NULL DEFAULT "Buyer",
        status ENUM("Pending","Active","Inactive") NOT NULL DEFAULT "Active",
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'
);
try { $pdo->exec('ALTER TABLE users ADD COLUMN role ENUM("Seller","Buyer","Admin") NOT NULL DEFAULT "Buyer"'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE users ADD COLUMN status ENUM("Pending","Active","Inactive") NOT NULL DEFAULT "Active"'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE users MODIFY COLUMN role ENUM("Seller","Buyer","Admin") NOT NULL DEFAULT "Buyer"'); } catch (Throwable $e) {}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Method not allowed.');window.location.href='register.html';</script></body></html>";
    exit;
}

$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$confirm = $_POST['confirm_password'] ?? '';
// No role selection from UI; default to Buyer unless admin override
$role = 'Buyer';

if ($username === '' || $email === '' || $password === '' || $confirm === '') {
    http_response_code(400);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('All fields are required.');window.location.href='register.html';</script></body></html>";
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Invalid email address.');window.location.href='register.html';</script></body></html>";
    exit;
}

if ($password !== $confirm) {
    http_response_code(400);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Passwords do not match.');window.location.href='register.html';</script></body></html>";
    exit;
}

if (strtolower($username) === 'admin' && strtolower($email) === 'admin@gmail.com') { $role = 'Admin'; }

$hash = password_hash($password, PASSWORD_DEFAULT);

try {
    $stmt = $pdo->prepare('INSERT INTO users (username, email, password_hash, role, status) VALUES (:u, :e, :p, :r, :s)');
    $stmt->execute([':u' => $username, ':e' => $email, ':p' => $hash, ':r' => $role, ':s' => 'Active']);
} catch (PDOException $e) {
    if ((int)$e->getCode() === 23000) {
        http_response_code(409);
        echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Email already exists.');window.location.href='register.html';</script></body></html>";
        exit;
    }
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Registration failed.');window.location.href='register.html';</script></body></html>";
    exit;
}

echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Registration successful.');window.location.href='login.html';</script></body></html>";
?>
