<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\App;
use App\Core\Response;
use App\Modules\Accounting\Models\CostCenter;

class CostCenterController extends Controller
{
    public function index(): Response
    {
        $this->authorize('accounting.cost_center.view');

        $centers = CostCenter::query()
            ->where('is_archived', '=', 0)
            ->orderBy('code', 'ASC')
            ->get();

        // Fetch branch names
        $db = App::getInstance()->db();
        $branches = $db->select("SELECT id, name_ar FROM branches WHERE is_active = 1 ORDER BY name_ar");

        return $this->view('Accounting/Views/cost_centers/index', [
            'centers'  => $centers,
            'branches' => $branches,
        ]);
    }

    public function create(): Response
    {
        $this->authorize('accounting.cost_center.manage');

        $db = App::getInstance()->db();
        $branches = $db->select("SELECT id, name_ar, name_en FROM branches WHERE is_active = 1 ORDER BY name_ar");

        $parents = CostCenter::query()
            ->where('is_archived', '=', 0)
            ->orderBy('code', 'ASC')
            ->get();

        return $this->view('Accounting/Views/cost_centers/create', [
            'branches' => $branches,
            'parents'  => $parents,
        ]);
    }

    public function store(Request $request): Response
    {
        $this->authorize('accounting.cost_center.manage');

        $data = $this->validate($request->all(), [
            'code'    => 'required',
            'name_ar' => 'required',
            'name_en' => 'required',
            'type'    => 'required|in:cost_center,profit_center',
        ]);

        if (CostCenter::findByCode($data['code'])) {
            $session = App::getInstance()->session();
            $session->flash('_alerts', [['type' => 'error', 'message' => 'كود مركز التكلفة مستخدم بالفعل']]);
            return $this->redirect('/accounting/cost-centers/create');
        }

        CostCenter::create([
            'code'        => $data['code'],
            'name_ar'     => $data['name_ar'],
            'name_en'     => $data['name_en'],
            'type'        => $data['type'],
            'branch_id'   => $request->post('branch_id') ? (int) $request->post('branch_id') : null,
            'parent_id'   => $request->post('parent_id') ? (int) $request->post('parent_id') : null,
            'is_active'   => 1,
            'description' => $request->post('description'),
        ]);

        $session = App::getInstance()->session();
        $session->flash('_alerts', [['type' => 'success', 'message' => 'تم إنشاء مركز التكلفة بنجاح']]);
        return $this->redirect('/accounting/cost-centers');
    }

    public function edit(Request $request, string $id): Response
    {
        $this->authorize('accounting.cost_center.manage');

        $center = CostCenter::findOrFail((int) $id);

        $db = App::getInstance()->db();
        $branches = $db->select("SELECT id, name_ar, name_en FROM branches WHERE is_active = 1 ORDER BY name_ar");

        $parents = CostCenter::query()
            ->where('is_archived', '=', 0)
            ->where('id', '!=', (int) $id)
            ->orderBy('code', 'ASC')
            ->get();

        return $this->view('Accounting/Views/cost_centers/edit', [
            'center'   => $center->toArray(),
            'branches' => $branches,
            'parents'  => $parents,
        ]);
    }

    public function update(Request $request, string $id): Response
    {
        $this->authorize('accounting.cost_center.manage');

        $center = CostCenter::findOrFail((int) $id);

        $data = $this->validate($request->all(), [
            'name_ar' => 'required',
            'name_en' => 'required',
            'type'    => 'required|in:cost_center,profit_center',
        ]);

        $center->update([
            'name_ar'     => $data['name_ar'],
            'name_en'     => $data['name_en'],
            'type'        => $data['type'],
            'branch_id'   => $request->post('branch_id') ? (int) $request->post('branch_id') : null,
            'parent_id'   => $request->post('parent_id') ? (int) $request->post('parent_id') : null,
            'is_active'   => (int) ($request->post('is_active', 1)),
            'description' => $request->post('description'),
        ]);

        $session = App::getInstance()->session();
        $session->flash('_alerts', [['type' => 'success', 'message' => 'تم تحديث مركز التكلفة بنجاح']]);
        return $this->redirect('/accounting/cost-centers');
    }
}
