<?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\Validator;
use App\Core\View;

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

        $products = Database::query(
            'SELECT id, nama_produk, harga, deskripsi, status, created_at, updated_at
             FROM products
             ORDER BY created_at DESC, id DESC'
        )->fetchAll();

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

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

        $input = [
            'nama_produk' => trim((string) $request->input('nama_produk', '')),
            'harga' => trim((string) $request->input('harga', '')),
            'deskripsi' => trim((string) $request->input('deskripsi', '')),
            'status' => trim((string) $request->input('status', 'aktif')),
        ];

        Session::flash('old_input', $input);

        $errors = Validator::make($input, [
            'nama_produk' => ['required', 'string', 'min:3', 'max:120'],
            'harga' => ['required', 'string'],
            'deskripsi' => ['max:2000'],
            'status' => ['required', 'string'],
        ]);

        if (! is_numeric($input['harga']) || (float) $input['harga'] < 0) {
            $errors['harga'][] = 'Harga harus berupa angka valid.';
        }

        if (! in_array($input['status'], ['aktif', 'nonaktif'], true)) {
            $errors['status'][] = 'Status produk tidak valid.';
        }

        if ($errors !== []) {
            Session::flash('errors', $errors);
            redirect('/admin/products');
        }

        $now = date('Y-m-d H:i:s');
        Database::query(
            'INSERT INTO products (nama_produk, harga, deskripsi, status, created_at, updated_at)
             VALUES (:nama_produk, :harga, :deskripsi, :status, :created_at, :updated_at)',
            [
                'nama_produk' => $input['nama_produk'],
                'harga' => $input['harga'],
                'deskripsi' => $input['deskripsi'] !== '' ? $input['deskripsi'] : null,
                'status' => $input['status'],
                'created_at' => $now,
                'updated_at' => $now,
            ]
        );

        AuditLogger::log('admin_product_create', \App\Core\Auth::id(), [
            'nama_produk' => $input['nama_produk'],
        ]);
        Session::flash('status', 'Produk berhasil ditambahkan.');
        redirect('/admin/products');
    }

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

        $productId = (int) $request->input('product_id', 0);
        $product = Database::query('SELECT id, status FROM products WHERE id = :id LIMIT 1', [
            'id' => $productId,
        ])->fetch();

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

        $newStatus = $product['status'] === 'aktif' ? 'nonaktif' : 'aktif';
        Database::query(
            'UPDATE products SET status = :status, updated_at = :updated_at WHERE id = :id',
            [
                'status' => $newStatus,
                'updated_at' => date('Y-m-d H:i:s'),
                'id' => $productId,
            ]
        );

        AuditLogger::log('admin_product_toggle', \App\Core\Auth::id(), [
            'product_id' => $productId,
            'status' => $newStatus,
        ]);
        Session::flash('status', 'Status produk diperbarui.');
        redirect('/admin/products');
    }

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

        $productId = (int) $request->input('product_id', 0);
        Database::query('DELETE FROM products WHERE id = :id', [
            'id' => $productId,
        ]);

        AuditLogger::log('admin_product_delete', \App\Core\Auth::id(), [
            'product_id' => $productId,
        ]);
        Session::flash('status', 'Produk berhasil dihapus.');
        redirect('/admin/products');
    }
}
