<?php
declare(strict_types=1);

namespace App\Modules\Admin;

use App\Core\AuditLogger;
use App\Core\Database;
use App\Core\Request;
use App\Core\Session;
use App\Core\View;

final class AdminPurchaseController
{
    public function index(Request $request): string
    {
        require_role('admin');

        $purchases = Database::query(
            'SELECT p.id, p.harga, p.bukti_transfer, p.status, p.created_at, p.updated_at,
                    u.nama AS user_name, u.email AS user_email, u.whatsapp AS user_whatsapp,
                    pr.nama_produk AS product_name
             FROM purchases p
             INNER JOIN users u ON u.id = p.user_id
             INNER JOIN products pr ON pr.id = p.product_id
             ORDER BY p.created_at DESC, p.id DESC'
        )->fetchAll();

        return View::renderTemplate('admin/purchases', [
            'purchases' => $purchases,
        ], 'admin/layout');
    }

    public function verify(Request $request): never
    {
        $this->updateStatus($request, 'verified');
    }

    public function complete(Request $request): never
    {
        $this->updateStatus($request, 'completed');
    }

    public function reject(Request $request): never
    {
        $this->updateStatus($request, 'rejected');
    }

    private function updateStatus(Request $request, string $status): never
    {
        require_role('admin');
        verify_csrf((string) $request->input('_token', ''));

        $purchaseId = (int) $request->input('purchase_id', 0);
        $purchase = Database::query('SELECT id, status FROM purchases WHERE id = :id LIMIT 1', [
            'id' => $purchaseId,
        ])->fetch();

        if (! is_array($purchase)) {
            abort(404, 'Pembelian tidak ditemukan.');
        }

        Database::query(
            'UPDATE purchases SET status = :status, updated_at = :updated_at WHERE id = :id',
            [
                'status' => $status,
                'updated_at' => date('Y-m-d H:i:s'),
                'id' => $purchaseId,
            ]
        );

        AuditLogger::log('admin_purchase_update', \App\Core\Auth::id(), [
            'purchase_id' => $purchaseId,
            'status' => $status,
        ]);
        Session::flash('status', 'Status pembelian diperbarui.');
        redirect('/admin/purchases');
    }
}
