<?php
declare(strict_types=1);

namespace App\Modules\Inventory\Services;

use App\Core\App;
use App\Core\EventBus;

final class AssetCustodyService
{
    public static function transfer(int $assetId, array $data): array
    {
        $db = App::getInstance()->db();
        $employee = App::getInstance()->currentEmployee();

        $asset = $db->selectOne("SELECT * FROM asset_register WHERE id = ?", [$assetId]);
        if (!$asset) {
            return ['success' => false, 'error' => 'الأصل غير موجود'];
        }

        $newEmployeeId = !empty($data['to_employee_id']) ? (int) $data['to_employee_id'] : null;
        $newLocation = $data['new_location'] ?? null;

        $db->beginTransaction();
        try {
            // Record history
            $db->insert('asset_custody_history', [
                'asset_id' => $assetId,
                'from_employee_id' => $asset['custodian_employee_id'] ?? null,
                'to_employee_id' => $newEmployeeId,
                'transfer_date' => $data['transfer_date'] ?? date('Y-m-d'),
                'reason' => $data['reason'] ?? null,
                'from_location' => $asset['site_location'] ?? null,
                'to_location' => $newLocation,
                'transferred_by' => $employee ? (int) $employee->id : null,
                'created_at' => date('Y-m-d H:i:s'),
            ]);

            // Update asset
            $updateData = ['updated_at' => date('Y-m-d H:i:s')];
            if ($newEmployeeId !== null || isset($data['to_employee_id'])) {
                $updateData['custodian_employee_id'] = $newEmployeeId;
            }
            if ($newLocation !== null) {
                $updateData['site_location'] = $newLocation;
            }
            $db->update('asset_register', $updateData, 'id = ?', [$assetId]);

            $db->commit();

            EventBus::dispatch('asset.custody_transferred', [
                'asset_id' => $assetId,
                'from_employee_id' => $asset['custodian_employee_id'] ?? null,
                'to_employee_id' => $newEmployeeId,
            ]);

            return ['success' => true];
        } catch (\Throwable $e) {
            $db->rollBack();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    public static function getHistory(int $assetId): array
    {
        $db = App::getInstance()->db();

        return $db->select(
            "SELECT ach.*,
                    ef.name_ar as from_name, et.name_ar as to_name, eb.name_ar as transferred_by_name
             FROM asset_custody_history ach
             LEFT JOIN employees ef ON ef.id = ach.from_employee_id
             LEFT JOIN employees et ON et.id = ach.to_employee_id
             LEFT JOIN employees eb ON eb.id = ach.transferred_by
             WHERE ach.asset_id = ?
             ORDER BY ach.transfer_date DESC, ach.id DESC",
            [$assetId]
        );
    }

    public static function getEmployeeAssets(int $employeeId): array
    {
        $db = App::getInstance()->db();

        return $db->select(
            "SELECT ar.*, ac.name_ar as category_name
             FROM asset_register ar
             LEFT JOIN asset_categories ac ON ac.id = ar.category_id
             WHERE ar.custodian_employee_id = ?
             ORDER BY ar.asset_name_ar",
            [$employeeId]
        );
    }
}
