<?php
// password_utils.php
// Helper untuk generate / simpan / verifikasi / hapus token reset (6-digit).
require_once __DIR__ . '/../Login/config.php';

if (session_status() === PHP_SESSION_NONE) session_start();

/**
 * Generate kode 6 digit sebagai string.
 */
function generate_code_6() {
    return str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
}

/**
 * Simpan token (hash) ke tabel password_resets.
 * Mencoba menyimpan kolom 'purpose' jika ada, jika tidak ada fallback tanpa purpose.
 *
 * @param PDO $pdo
 * @param string $email
 * @param string $plainCode
 * @param int $ttlSeconds
 * @param string $purpose
 * @return bool
 */
function save_password_token(PDO $pdo, string $email, string $plainCode, int $ttlSeconds = 900, string $purpose = 'reset') : bool {
    $hash = password_hash($plainCode, PASSWORD_DEFAULT);
    $expires_at = date('Y-m-d H:i:s', time() + $ttlSeconds);

    try {
        $ins = $pdo->prepare("INSERT INTO password_resets (email, token_hash, expires_at, created_at, purpose) VALUES (?, ?, ?, NOW(), ?)");
        $ins->execute([$email, $hash, $expires_at, $purpose]);
        return true;
    } catch (Throwable $e) {
        // fallback: jika kolom purpose tidak ada
        try {
            $ins = $pdo->prepare("INSERT INTO password_resets (email, token_hash, expires_at) VALUES (?, ?, ?)");
            $ins->execute([$email, $hash, $expires_at]);
            return true;
        } catch (Throwable $e2) {
            error_log("save_password_token error: " . $e2->getMessage());
            return false;
        }
    }
}

/**
 * Ambil row token terbaru untuk email (dan purpose jika ada).
 * Mengembalikan associative array atau false jika tidak ada.
 */
function get_latest_token_row(PDO $pdo, string $email, string $purpose = 'reset') {
    try {
        $stmt = $pdo->prepare("SELECT id, token_hash, expires_at, created_at FROM password_resets WHERE email = ? AND (purpose = ? OR ? = ?) ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([$email, $purpose, 'x', 'x']);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Throwable $e) {
        // fallback tanpa purpose
        try {
            $stmt = $pdo->prepare("SELECT id, token_hash, expires_at, created_at FROM password_resets WHERE email = ? ORDER BY created_at DESC LIMIT 1");
            $stmt->execute([$email]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Throwable $e2) {
            error_log("get_latest_token_row error: " . $e2->getMessage());
            return false;
        }
    }
}

/**
 * Verifikasi kode plain terhadap hash (password_verify)
 */
function verify_code_with_hash(string $plainCode, string $hash) : bool {
    return password_verify($plainCode, $hash);
}

/**
 * Hapus token(s) untuk email. Jika purpose diisi maka hapus yang sesuai, 
 * tapi fallback hapus semua entri email ini.
 */
function delete_tokens_for_email(PDO $pdo, string $email, string $purpose = null) : void {
    try {
        if ($purpose !== null) {
            $del = $pdo->prepare("DELETE FROM password_resets WHERE email = ? AND (purpose = ? OR ? = ?)");
            $del->execute([$email, $purpose, 'x','x']);
        } else {
            $del = $pdo->prepare("DELETE FROM password_resets WHERE email = ?");
            $del->execute([$email]);
        }
    } catch (Throwable $e) {
        // fallback: hapus semua row email
        try {
            $del = $pdo->prepare("DELETE FROM password_resets WHERE email = ?");
            $del->execute([$email]);
        } catch (Throwable $e2) {
            error_log("delete_tokens_for_email error: " . $e2->getMessage());
        }
    }
}
