<?php
declare(strict_types=1);

namespace App\Modules\Branches\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Branches\Models\Branch;

class BranchController extends Controller
{
    public function index(Request $request): Response
    {
        $db = App::getInstance()->db();
        $branches = $db->select("
            SELECT b.*,
                   (SELECT COUNT(*) FROM employees e WHERE e.branch_id = b.id AND e.is_archived = 0 AND e.is_active = 1) as emp_count
            FROM branches b
            ORDER BY b.name_ar
        ");
        return $this->view('Branches.Views.index', ['branches' => $branches]);
    }

    public function create(Request $request): Response
    {
        return $this->view('Branches.Views.create', []);
    }

    public function store(Request $request): Response
    {
        $data = $this->validate($request->all(), [
            'branch_code'  => 'required|string|min:2|max:50',
            'name_ar'      => 'required|string|min:2|max:200',
            'name_en'      => 'nullable|string|max:200',
            'address'      => 'nullable|string|max:1000',
            'phone'        => 'nullable|string|max:20',
            'manager_name' => 'nullable|string|max:200',
        ]);

        $existing = App::getInstance()->db()->selectOne("SELECT id FROM branches WHERE branch_code = ?", [$data['branch_code']]);
        if ($existing) {
            return $this->redirect('/branches/create')->withError('كود الفرع مستخدم بالفعل');
        }

        Branch::create([
            'branch_code'  => $data['branch_code'],
            'name_ar'      => $data['name_ar'],
            'name_en'      => $data['name_en'] ?? null,
            'address'      => $data['address'] ?? null,
            'phone'        => $data['phone'] ?? null,
            'manager_name' => $data['manager_name'] ?? null,
            'is_active'    => 1,
        ]);

        return $this->redirect('/branches')->withSuccess('تم إنشاء الفرع بنجاح');
    }

    public function show(Request $request, string $id): Response
    {
        $branch = Branch::find((int) $id);
        if (!$branch) {
            return $this->redirect('/branches')->withError('الفرع غير موجود');
        }

        return $this->view('Branches.Views.show', [
            'branch'    => $branch,
            'empCount'  => $branch->getEmployeeCount(),
            'memCount'  => $branch->getMemberCount(),
        ]);
    }

    public function edit(Request $request, string $id): Response
    {
        $branch = Branch::find((int) $id);
        if (!$branch) {
            return $this->redirect('/branches')->withError('الفرع غير موجود');
        }
        return $this->view('Branches.Views.edit', ['branch' => $branch]);
    }

    public function update(Request $request, string $id): Response
    {
        $branch = Branch::find((int) $id);
        if (!$branch) {
            return $this->redirect('/branches')->withError('الفرع غير موجود');
        }

        $data = $this->validate($request->all(), [
            'name_ar'      => 'required|string|min:2|max:200',
            'name_en'      => 'nullable|string|max:200',
            'address'      => 'nullable|string|max:1000',
            'phone'        => 'nullable|string|max:20',
            'manager_name' => 'nullable|string|max:200',
            'is_active'    => 'nullable|in:0,1',
        ]);

        $branch->update([
            'name_ar'      => $data['name_ar'],
            'name_en'      => $data['name_en'] ?? null,
            'address'      => $data['address'] ?? null,
            'phone'        => $data['phone'] ?? null,
            'manager_name' => $data['manager_name'] ?? null,
            'is_active'    => isset($data['is_active']) ? (int) $data['is_active'] : (int) $branch->is_active,
        ]);

        return $this->redirect('/branches')->withSuccess('تم تحديث الفرع بنجاح');
    }
}