<?php
class TransferTypeController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('transfer-types/index', [
            'title' => lang('board.transfer_types'),
            'breadcrumbs' => [
                ['label' => lang('board.transfers_module'), 'url' => '/transfers'],
                ['label' => lang('board.transfer_types')]
            ],
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw = (int) $request->get('draw', 1);
        $start = (int) $request->get('start', 0);
        $length = (int) $request->get('length', 25);
        $search = $request->get('search')['value'] ?? '';

        $where = '1=1';
        $params = [];
        if ($search) {
            $where .= " AND (type_code LIKE ? OR name_en LIKE ? OR name_ar LIKE ?)";
            $params = ["%{$search}%", "%{$search}%", "%{$search}%"];
        }

        $total = (int) $db->fetchColumn("SELECT COUNT(*) FROM transfer_types");
        $filtered = (int) $db->fetchColumn("SELECT COUNT(*) FROM transfer_types WHERE {$where}", $params);

        $rows = $db->fetchAll("SELECT * FROM transfer_types WHERE {$where} ORDER BY type_code LIMIT {$length} OFFSET {$start}", $params);

        $data = [];
        foreach ($rows as $row) {
            $actions = '<a href="/transfer-types/' . $row['id'] . '/edit" class="btn btn-sm btn-outline-warning me-1"><i class="fas fa-edit"></i></a>';
            $data[] = [
                'id' => $row['id'],
                'code' => e($row['type_code']),
                'name' => e(current_lang() === 'ar' ? ($row['name_ar'] ?: $row['name_en']) : $row['name_en']),
                'fee_type' => e($row['fee_type']),
                'fee_amount' => money($row['fee_amount']),
                'board_approval' => $row['requires_board_approval'] ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>',
                'status' => $row['is_active'] ? status_badge('active') : status_badge('expired'),
                'actions' => $actions,
            ];
        }

        $this->json(['draw' => $draw, 'recordsTotal' => $total, 'recordsFiltered' => $filtered, 'data' => $data]);
    }

    public function create(Request $request): void
    {
        $this->view('transfer-types/form', [
            'title' => lang('board.create_transfer_type'),
            'breadcrumbs' => [
                ['label' => lang('board.transfers_module'), 'url' => '/transfers'],
                ['label' => lang('board.transfer_types'), 'url' => '/transfer-types'],
                ['label' => lang('common.create')]
            ],
            'type' => null,
            'formAction' => '/transfer-types',
        ]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }

        $validator = new Validator($request->all(), [
            'type_code'              => 'required|string|max:20|unique:transfer_types,type_code',
            'name_en'                => 'required|string|max:200',
            'name_ar'                => 'required|string|max:200',
            'description_en'         => 'nullable|string|max:5000',
            'description_ar'         => 'nullable|string|max:5000',
            'requires_board_approval'=> 'nullable|boolean',
            'fee_type'               => 'required|in:none,fixed,percentage_of_subscription',
            'fee_amount'             => 'nullable|decimal|min:0',
            'fee_percentage'         => 'nullable|decimal|min:0|max:100',
        ]);

        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }

        $data = $validator->validated();
        $data['requires_board_approval'] = $request->post('requires_board_approval') ? 1 : 0;
        $data['is_active'] = 1;
        $id = $this->db()->insert('transfer_types', $data);

        $this->audit('create', 'transfer_types', $id, 'Created transfer type: ' . $data['type_code']);
        $this->json(['success' => true, 'message' => lang('board.type_created'), 'redirect' => '/transfer-types']);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $type = $this->db()->fetchOne("SELECT * FROM transfer_types WHERE id = ?", [$id]);
        if (!$type) { $this->abort(404); return; }

        $this->view('transfer-types/form', [
            'title' => lang('board.edit_transfer_type'),
            'breadcrumbs' => [
                ['label' => lang('board.transfers_module'), 'url' => '/transfers'],
                ['label' => lang('board.transfer_types'), 'url' => '/transfer-types'],
                ['label' => lang('common.edit')]
            ],
            'type' => $type,
            'formAction' => '/transfer-types/' . $id,
        ]);
    }

    public function update(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }

        $old = $this->db()->fetchOne("SELECT * FROM transfer_types WHERE id = ?", [$id]);
        if (!$old) { $this->json(['success' => false, 'message' => 'Not found'], 404); return; }

        $validator = new Validator($request->all(), [
            'type_code'              => 'required|string|max:20|unique:transfer_types,type_code,' . $id,
            'name_en'                => 'required|string|max:200',
            'name_ar'                => 'required|string|max:200',
            'description_en'         => 'nullable|string|max:5000',
            'description_ar'         => 'nullable|string|max:5000',
            'requires_board_approval'=> 'nullable|boolean',
            'fee_type'               => 'required|in:none,fixed,percentage_of_subscription',
            'fee_amount'             => 'nullable|decimal|min:0',
            'fee_percentage'         => 'nullable|decimal|min:0|max:100',
            'is_active'              => 'nullable|boolean',
        ]);

        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }

        $data = $validator->validated();
        $data['requires_board_approval'] = $request->post('requires_board_approval') ? 1 : 0;
        $data['is_active'] = $request->post('is_active') ? 1 : 0;
        $this->db()->update('transfer_types', $data, 'id = ?', [$id]);

        $this->audit('update', 'transfer_types', $id, 'Updated transfer type: ' . $data['type_code'], $old, $data);
        $this->json(['success' => true, 'message' => lang('board.type_updated'), 'redirect' => '/transfer-types']);
    }
}