<?php
require_once 'config/config.php';
session_start();

$lang_code = $_SESSION['language'] ?? 'english';
require_once "languages/$lang_code.php";

if (!isset($_SESSION['reset_email']) || !isset($_SESSION['code_verified']) || $_SESSION['code_verified'] !== true) {
    header("Location: forgot_password.php");
    exit;
}

$message = '';
$redirect = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $new = trim($_POST['new_password']);
    $confirm = trim($_POST['confirm_password']);

    if (empty($new) || empty($confirm)) {
        $message = "<div class='alert alert-danger'>{$lang['please_fill_all_fields']}</div>";
    } elseif ($new !== $confirm) {
        $message = "<div class='alert alert-danger'>{$lang['passwords_not_match']}</div>";
    } else {
        $hashed = password_hash($new, PASSWORD_DEFAULT);
        $stmt = $conn->prepare("UPDATE users SET password = ? WHERE email = ?");
        $stmt->bind_param("ss", $hashed, $_SESSION['reset_email']);
        if ($stmt->execute()) {
            $message = "<div class='alert alert-success'>{$lang['password_changed_successfully']}</div>";
            unset($_SESSION['reset_email'], $_SESSION['verification_code'], $_SESSION['code_verified']);
            $redirect = true;
        } else {
            $message = "<div class='alert alert-danger'>{$lang['something_went_wrong']}</div>";
        }
        $stmt->close();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?= $lang['reset_password'] ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <?php if ($redirect): ?>
    <meta http-equiv="refresh" content="3;url=auth/login.php">
    <?php endif; ?>
</head>
<body>

<div class="container mt-5" style="max-width: 500px;">
    <img src="images/logo.png" class="d-block mx-auto mb-4" width="150" alt="Logo">
    <h3 class="text-center mb-4"><?= $lang['reset_password'] ?></h3>
    <?= $message ?>
    <form method="POST">
        <div class="mb-3">
            <label class="form-label"><?= $lang['new_password'] ?></label>
            <input type="password" name="new_password" class="form-control" required>
        </div>
        <div class="mb-3">
            <label class="form-label"><?= $lang['confirm_password'] ?></label>
            <input type="password" name="confirm_password" class="form-control" required>
        </div>
        <button type="submit" class="btn btn-primary w-100"><?= $lang['update'] ?></button>
    </form>
</div>

</body>
</html>
