<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Inventory\Models\AssetRegister;
use App\Modules\Inventory\Models\DepreciationEntry;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Services\DepreciationService;

class AssetController extends Controller
{
    public function index(Request $request): Response
    {
        $filters = [
            'q'            => trim((string) $request->get('q', '')),
            'status'       => trim((string) $request->get('status', '')),
            'warehouse_id' => trim((string) $request->get('warehouse_id', '')),
        ];

        $page = max(1, (int) $request->get('page', 1));
        $result = AssetRegister::search($filters, 25, $page);

        return $this->view('Inventory.Views.assets.index', [
            'assets'     => $result['data'],
            'pagination' => $result['pagination'],
            'filters'    => $filters,
            'statuses'   => AssetRegister::getStatuses(),
            'warehouses' => Warehouse::allActive(),
        ]);
    }

    public function show(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();

        $asset = $db->selectOne(
            "SELECT ar.*, i.`name_ar` as item_name, i.`sku`, w.`name_ar` as warehouse_name
             FROM `asset_register` ar
             JOIN `inventory_items` i ON i.`id` = ar.`item_id`
             JOIN `warehouses` w ON w.`id` = ar.`warehouse_id`
             WHERE ar.`id` = ?",
            [(int) $id]
        );

        if (!$asset) {
            return $this->redirect('/inventory/assets')->withError('الأصل غير موجود');
        }

        $depreciationHistory = DepreciationEntry::getForAsset((int) $id);

        return $this->view('Inventory.Views.assets.show', [
            'asset'               => $asset,
            'depreciationHistory' => $depreciationHistory,
            'methods'             => AssetRegister::getDepreciationMethods(),
        ]);
    }

    public function dispose(Request $request, string $id): Response
    {
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();

        $asset = $db->selectOne("SELECT * FROM `asset_register` WHERE `id` = ?", [(int) $id]);
        if (!$asset) {
            return $this->redirect('/inventory/assets')->withError('الأصل غير موجود');
        }

        if ($asset['status'] !== 'active') {
            return $this->redirect('/inventory/assets/' . $id)->withError('الأصل غير نشط — لا يمكن التصرف فيه');
        }

        $disposalValue = trim((string) $request->post('disposal_value', '0'));
        $reason = trim((string) $request->post('disposal_reason', ''));

        $db->update('asset_register', [
            'status'           => 'disposed',
            'disposed_at'      => date('Y-m-d'),
            'disposal_value'   => $disposalValue,
            'disposal_reason'  => $reason ?: null,
            'updated_at'       => date('Y-m-d H:i:s'),
            'updated_by'       => $employee ? (int) $employee->id : null,
        ], '`id` = ?', [(int) $id]);

        return $this->redirect('/inventory/assets/' . $id)->withSuccess('تم تسجيل التصرف في الأصل');
    }

    public function runDepreciation(Request $request): Response
    {
        $month = trim((string) $request->post('period_month', date('Y-m')));
        if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
            return $this->redirect('/inventory/assets')->withError('صيغة الشهر غير صحيحة');
        }

        $count = DepreciationService::runMonthlyDepreciation($month);

        return $this->redirect('/inventory/assets')->withSuccess('تم تشغيل الإهلاك لشهر ' . $month . ' — ' . $count . ' أصل');
    }
}
