<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Controllers;

use App\Core\Controller;
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(): Response
    {
        $this->authorize('accounting.cost_center.manage');

        $data = $this->validate($_POST, [
            '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'   => !empty($_POST['branch_id']) ? (int) $_POST['branch_id'] : null,
            'parent_id'   => !empty($_POST['parent_id']) ? (int) $_POST['parent_id'] : null,
            'is_active'   => 1,
            'description' => $_POST['description'] ?? null,
        ]);

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

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

        $center = CostCenter::findOrFail($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', '!=', $id)
            ->orderBy('code', 'ASC')
            ->get();

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

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

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

        $data = $this->validate($_POST, [
            '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'   => !empty($_POST['branch_id']) ? (int) $_POST['branch_id'] : null,
            'parent_id'   => !empty($_POST['parent_id']) ? (int) $_POST['parent_id'] : null,
            'is_active'   => (int) ($_POST['is_active'] ?? 1),
            'description' => $_POST['description'] ?? null,
        ]);

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