<?php
namespace Tshen\Controllers;
use Tshen\Database; use function Tshen\view; use function Tshen\redirect;

class AdminController {
    public function index() {
        if (($_SESSION['role'] ?? '') !== 'admin') { redirect('/'); }
        $codes = Database::run('SELECT code,credits,used_by FROM credit_codes ORDER BY id DESC')->fetchAll();
        return view('admin/index', ['title'=>'Admin','codes'=>$codes]);
    }
    public function issueCode() {
        if (($_SESSION['role'] ?? '') !== 'admin') { redirect('/'); }
        if (!\Tshen\csrf_check()) { \Tshen\flash('error','Invalid request.'); return redirect('/admin'); }
        $credits = (int)($_POST['credits'] ?? 0);
        if ($credits <= 0) redirect('/admin');
        $code = strtoupper(substr(bin2hex(random_bytes(8)),0,10));
        Database::run('INSERT INTO credit_codes (code,credits) VALUES (?,?)', [$code,$credits]);
        \Tshen\flash('success','Code issued: ' . $code);
        redirect('/admin');
    }
}