<?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;

class AssetCustodyController extends Controller
{
    public function index(Request $request): Response
    {
        $this->authorize('asset.view');
        $db = App::getInstance()->db();

        $employeeId = (int) $request->get('employee_id', 0);
        $location = $request->get('location', '');
        $where = 'a.status = ?';
        $params = ['active'];

        if ($employeeId) {
            $where .= ' AND a.custodian_employee_id = ?';
            $params[] = $employeeId;
        }
        if ($location) {
            $where .= ' AND a.site_location LIKE ?';
            $params[] = '%' . $location . '%';
        }

        $assets = $db->select(
            "SELECT a.*, i.name_ar as item_name, e.full_name_ar as custodian_name, w.name_ar as warehouse_name
             FROM asset_register a
             JOIN inventory_items i ON i.id = a.item_id
             LEFT JOIN employees e ON e.id = a.custodian_employee_id
             LEFT JOIN warehouses w ON w.id = a.warehouse_id
             WHERE {$where}
             ORDER BY a.site_location, i.name_ar",
            $params
        );

        $employees = $db->select("SELECT id, full_name_ar FROM employees WHERE is_archived = 0 ORDER BY full_name_ar");

        return $this->view('Inventory.Views.assets.custody_index', [
            'assets' => $assets,
            'employees' => $employees,
            'employee_id' => $employeeId,
            'location' => $location,
        ]);
    }

    public function transfer(Request $request, string $id): Response
    {
        $this->authorize('asset.manage');
        $db = App::getInstance()->db();

        $asset = $db->selectOne(
            "SELECT a.*, i.name_ar as item_name, e.full_name_ar as current_custodian_name
             FROM asset_register a
             JOIN inventory_items i ON i.id = a.item_id
             LEFT JOIN employees e ON e.id = a.custodian_employee_id
             WHERE a.id = ?",
            [(int) $id]
        );

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

        $employees = $db->select("SELECT id, full_name_ar FROM employees WHERE is_archived = 0 ORDER BY full_name_ar");

        return $this->view('Inventory.Views.assets.custody_transfer', [
            'asset' => $asset,
            'employees' => $employees,
        ]);
    }

    public function storeTransfer(Request $request, string $id): Response
    {
        $this->authorize('asset.manage');
        $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/custody')->withError('الأصل غير موجود');
        }

        $toEmployeeId = $request->post('to_employee_id') ? (int) $request->post('to_employee_id') : null;
        $toLocation = $request->post('to_location', '');

        $db->beginTransaction();
        try {
            $db->insert('asset_custody_history', [
                'asset_id' => (int) $id,
                'from_employee_id' => $asset['custodian_employee_id'] ? (int) $asset['custodian_employee_id'] : null,
                'to_employee_id' => $toEmployeeId,
                'from_location' => $asset['site_location'],
                'to_location' => $toLocation,
                'transfer_date' => $request->post('transfer_date', date('Y-m-d')),
                'reason' => $request->post('reason'),
                'notes' => $request->post('notes'),
                'created_by' => $employee ? (int) $employee->id : null,
            ]);

            $db->update('asset_register', [
                'custodian_employee_id' => $toEmployeeId,
                'site_location' => $toLocation ?: $asset['site_location'],
                'custody_date' => date('Y-m-d'),
            ], 'id = ?', [(int) $id]);

            $db->commit();
            return $this->redirect('/inventory/assets/custody')->withSuccess('تم نقل عهدة الأصل بنجاح');
        } catch (\Throwable $e) {
            $db->rollBack();
            return $this->redirect('/inventory/assets/custody/' . $id . '/transfer')->withError('خطأ: ' . $e->getMessage());
        }
    }

    public function history(Request $request, string $id): Response
    {
        $this->authorize('asset.view');
        $db = App::getInstance()->db();

        $asset = $db->selectOne(
            "SELECT a.*, i.name_ar as item_name FROM asset_register a JOIN inventory_items i ON i.id = a.item_id WHERE a.id = ?",
            [(int) $id]
        );

        $history = $db->select(
            "SELECT h.*, fe.full_name_ar as from_employee_name, te.full_name_ar as to_employee_name, ce.full_name_ar as created_by_name
             FROM asset_custody_history h
             LEFT JOIN employees fe ON fe.id = h.from_employee_id
             LEFT JOIN employees te ON te.id = h.to_employee_id
             LEFT JOIN employees ce ON ce.id = h.created_by
             WHERE h.asset_id = ?
             ORDER BY h.transfer_date DESC, h.created_at DESC",
            [(int) $id]
        );

        return $this->view('Inventory.Views.assets.custody_history', [
            'asset' => $asset,
            'history' => $history,
        ]);
    }
}
