<?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='login.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,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'
);

// Ensure role and status columns exist for the role feature
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='login.html';</script></body></html>";
    exit;
}

$identifier = trim($_POST['identifier'] ?? '');
$password = $_POST['password'] ?? '';

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

try {
    $stmt = $pdo->prepare('SELECT id, username, email, password_hash, role, status FROM users WHERE email = :id OR username = :id LIMIT 1');
    $stmt->execute([':id' => $identifier]);
    $user = $stmt->fetch();
} catch (Throwable $e) {
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Login failed.');window.location.href='login.html';</script></body></html>";
    exit;
}

if (!$user) {
    http_response_code(401);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Invalid username/email or password.');window.location.href='login.html';</script></body></html>";
    exit;
}

$hash = (string)($user['password_hash'] ?? '');
$isHashed = ($hash !== '' && substr($hash, 0, 1) === '$');
$valid = $isHashed ? password_verify($password, $hash) : hash_equals($hash, (string)$password);

if (!$valid) {
    http_response_code(401);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Invalid username/email or password.');window.location.href='login.html';</script></body></html>";
    exit;
}

$status = (string)($user['status'] ?? 'Active');
if ($status === 'Inactive') {
    http_response_code(403);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('You have been blocked by the admin.');window.location.href='login.html';</script></body></html>";
    exit;
}

session_start();
$_SESSION['user_id'] = (int)$user['id'];
$_SESSION['username'] = (string)$user['username'];
$_SESSION['email'] = (string)$user['email'];
$_SESSION['role'] = (string)($user['role'] ?? 'Buyer');

$isAdmin = (strtolower((string)$user['username']) === 'admin' && strtolower((string)$user['email']) === 'admin@gmail.com');
if ($isAdmin) { $_SESSION['role'] = 'Admin'; }
$target = $isAdmin ? ('admin-dashboard.php?user=' . urlencode((string)$user['username'])) : 'index-2.php';
echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Login successfully');window.location.href='" . $target . "';</script></body></html>";
?>
