<?php
// reset_submit.php
require_once __DIR__ . '/../Login/config.php';
if (session_status() === PHP_SESSION_NONE) session_start();

function redirect_with_msg($type='success', $msg='') {
    // arahkan ke login atau forgot dengan pesan sederhana
    if ($type === 'success') {
        header('Location: ../login/login.php?reset=1');
    } else {
        header('Location: forgot.php?error=' . urlencode($msg));
    }
    exit;
}

// Ambil POST
$email = trim($_POST['email'] ?? '');
$token = trim($_POST['token'] ?? '');
$pw = $_POST['password'] ?? '';
$pw2 = $_POST['password2'] ?? '';

if ($email === '' || $token === '' || $pw === '' || $pw2 === '') {
    redirect_with_msg('error', 'Form tidak lengkap.');
}
if ($pw !== $pw2) {
    redirect_with_msg('error', 'Password konfirmasi tidak cocok.');
}
if (strlen($pw) < 6) {
    redirect_with_msg('error', 'Password minimal 6 karakter.');
}

try {
    // Ambil latest token row
    $stmt = $pdo->prepare("SELECT id, token_hash, expires_at FROM password_resets WHERE email = ? ORDER BY created_at DESC LIMIT 1");
    $stmt->execute([$email]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        redirect_with_msg('error', 'Token tidak ditemukan.');
    }

    if (strtotime($row['expires_at']) < time()) {
        redirect_with_msg('error', 'Token sudah kadaluarsa.');
    }

    if (!password_verify($token, $row['token_hash'])) {
        redirect_with_msg('error', 'Token tidak valid.');
    }

    // Semua ok -> update password user
    $hash = password_hash($pw, PASSWORD_DEFAULT);
    $upd = $pdo->prepare("UPDATE users SET password = ? WHERE email = ?");
    $upd->execute([$hash, $email]);

    // Hapus semua entri reset untuk email ini (atau hapus row yang dipakai)
    $del = $pdo->prepare("DELETE FROM password_resets WHERE email = ?");
    $del->execute([$email]);

    // Redirect ke login dengan flag sukses
    redirect_with_msg('success', '');
} catch (Throwable $e) {
    error_log("reset_submit error: " . $e->getMessage());
    redirect_with_msg('error', 'Terjadi kesalahan server.');
}
