<?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='forgot-password.html';</script></body></html>";
    exit;
}

try {
    $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'
    );
} 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='forgot-password.html';</script></body></html>";
    exit;
}

$identifier = trim($_POST['identifier'] ?? '');
$old = $_POST['old_password'] ?? '';
$new = $_POST['new_password'] ?? '';
$confirm = $_POST['confirm_password'] ?? '';

if ($identifier === '' || $old === '' || $new === '' || $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='forgot-password.html';</script></body></html>";
    exit;
}

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

try {
    $stmt = $pdo->prepare('SELECT id, username, email, password_hash, 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('Request failed.');window.location.href='forgot-password.html';</script></body></html>";
    exit;
}

if (!$user) {
    http_response_code(404);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('User not found.');window.location.href='forgot-password.html';</script></body></html>";
    exit;
}

if ((string)($user['status'] ?? 'Active') === 'Inactive') {
    http_response_code(403);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Your account is blocked.');window.location.href='forgot-password.html';</script></body></html>";
    exit;
}

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

if (!$valid) {
    http_response_code(401);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Old password is incorrect.');window.location.href='forgot-password.html';</script></body></html>";
    exit;
}

$newHash = password_hash($new, PASSWORD_DEFAULT);
try {
    $upd = $pdo->prepare('UPDATE users SET password_hash=:ph WHERE id=:id');
    $upd->execute([':ph' => $newHash, ':id' => (int)$user['id']]);
} catch (Throwable $e) {
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Failed to update password.');window.location.href='forgot-password.html';</script></body></html>";
    exit;
}

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

