<?php
require_once __DIR__ . '/db.php';

if (isset($_SESSION['user_id'])) {
    header('Location: dashboard.php');
    exit();
}

$userId = (int) ($_SESSION['password_reset_verified_user_id'] ?? 0);
$resetCodeId = (int) ($_SESSION['password_reset_verified_code_id'] ?? 0);
$newPassword = $_POST['new_password'] ?? '';
$confirmPassword = $_POST['confirm_password'] ?? '';

if ($userId <= 0 || $resetCodeId <= 0) {
    header('Location: forgot_password.php');
    exit();
}

if (strlen($newPassword) < 4) {
    header('Location: reset_password.php?error=weak_password');
    exit();
}

if ($newPassword !== $confirmPassword) {
    header('Location: reset_password.php?error=password_mismatch');
    exit();
}

$stmt = $conn->prepare("
    SELECT id, expires_at, used_at
    FROM password_reset_codes
    WHERE id = ? AND user_id = ?
    LIMIT 1
");
$stmt->bind_param('ii', $resetCodeId, $userId);
$stmt->execute();
$resetCode = $stmt->get_result()->fetch_assoc();

if (!$resetCode || !empty($resetCode['used_at']) || strtotime((string) $resetCode['expires_at']) < time()) {
    unset(
        $_SESSION['password_reset_user_id'],
        $_SESSION['password_reset_code_id'],
        $_SESSION['password_reset_email'],
        $_SESSION['password_reset_verified_user_id'],
        $_SESSION['password_reset_verified_code_id']
    );
    header('Location: forgot_password.php?error=expired');
    exit();
}

$hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

$conn->begin_transaction();

$updatePassword = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
$updatePassword->bind_param('si', $hashedPassword, $userId);
$updatePassword->execute();

$markUsed = $conn->prepare("UPDATE password_reset_codes SET used_at = NOW() WHERE id = ?");
$markUsed->bind_param('i', $resetCodeId);
$markUsed->execute();

$userStmt = $conn->prepare("SELECT nama, jabatan, role FROM users WHERE id = ? LIMIT 1");
$userStmt->bind_param('i', $userId);
$userStmt->execute();
$user = $userStmt->get_result()->fetch_assoc();

if ($user) {
    add_user_log(
        $conn,
        $userId,
        (string) $user['nama'],
        (string) $user['jabatan'],
        (string) $user['role'],
        'Reset kata laluan melalui emel verifikasi'
    );
}

$conn->commit();

unset(
    $_SESSION['password_reset_user_id'],
    $_SESSION['password_reset_code_id'],
    $_SESSION['password_reset_email'],
    $_SESSION['password_reset_verified_user_id'],
    $_SESSION['password_reset_verified_code_id']
);

header('Location: login.php?success=password_reset');
exit();
