<?php
// change_confirm_submit.php
require_once __DIR__ . '/../Login/config.php';
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: ../Login/login.php');
    exit;
}

$userId = $_SESSION['user_id'];
$token = trim($_POST['token'] ?? '');
$pw = $_POST['password'] ?? '';
$pw2 = $_POST['password2'] ?? '';

if ($token === '' || $pw === '' || $pw2 === '') {
    $_SESSION['change_confirm_msg'] = "Form tidak lengkap.";
    header('Location: change_confirm.php');
    exit;
}
if ($pw !== $pw2) {
    $_SESSION['change_confirm_msg'] = "Password konfirmasi tidak cocok.";
    header('Location: change_confirm.php');
    exit;
}
if (!preg_match('/^\d{6}$/', $token)) {
    $_SESSION['change_confirm_msg'] = "Kode tidak valid.";
    header('Location: change_confirm.php');
    exit;
}

// ambil email user
$stmt = $pdo->prepare("SELECT email FROM users WHERE id = ? LIMIT 1");
$stmt->execute([$userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) {
    $_SESSION['change_confirm_msg'] = "User tidak ditemukan.";
    header('Location: profile_change_request.php');
    exit;
}
$email = $user['email'];

// ambil latest token untuk email ini (kita cari yang belum expired dan purpose confirm_change jika ada)
try {
    // prefer query dengan purpose (jika kolom ada)
    $stmt = $pdo->prepare("SELECT id, token_hash, expires_at FROM password_resets WHERE email = ? AND (purpose = 'confirm_change' OR ? = ?) ORDER BY created_at DESC LIMIT 1");
    $stmt->execute([$email, 'x', 'x']);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    // fallback jika kolom purpose tidak ada: ambil berdasarkan email
    $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) {
    $_SESSION['change_confirm_msg'] = "Kode tidak ditemukan. Minta kode baru di halaman Akun.";
    header('Location: profile_change_request.php');
    exit;
}

if (strtotime($row['expires_at']) < time()) {
    $_SESSION['change_confirm_msg'] = "Kode sudah kadaluarsa. Minta kode baru di halaman Akun.";
    header('Location: profile_change_request.php');
    exit;
}

// cek token
if (!password_verify($token, $row['token_hash'])) {
    $_SESSION['change_confirm_msg'] = "Kode salah.";
    header('Location: profile_change_request.php');
    exit;
}

// token valid -> update password
$hash = password_hash($pw, PASSWORD_DEFAULT);
$upd = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
$upd->execute([$hash, $userId]);

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

// option: destroy session older? keep user logged in
$_SESSION['change_confirm_msg'] = "Password berhasil diubah.";
header('Location: profile_change_request.php');
exit;
