<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\CompanyModel;

/**
 * إدارة الشركات - ظاهر فقط للسوبر أدمن (Multi-Company)
 */
class CompanyController extends BaseController
{
    public function index()
    {
        if (! $this->isSuperAdmin()) return redirect()->to('/admin/dashboard');

        $companies = (new CompanyModel())->findAll();
        return view('admin/companies/index', ['companies' => $companies]);
    }

    public function create()
    {
        if (! $this->isSuperAdmin()) return redirect()->to('/admin/dashboard');
        return view('admin/companies/form', ['company' => null]);
    }

    public function store()
    {
        if (! $this->isSuperAdmin()) return redirect()->to('/admin/dashboard');
        (new CompanyModel())->insert($this->companyData());
        return redirect()->to('/admin/companies')->with('message', lang('App.saved_successfully'));
    }

    public function edit($id)
    {
        if (! $this->isSuperAdmin()) return redirect()->to('/admin/dashboard');
        $company = (new CompanyModel())->find($id);
        return view('admin/companies/form', ['company' => $company]);
    }

    public function update($id)
    {
        if (! $this->isSuperAdmin()) return redirect()->to('/admin/dashboard');
        (new CompanyModel())->update($id, $this->companyData());
        return redirect()->to('/admin/companies')->with('message', lang('App.saved_successfully'));
    }

    private function companyData(): array
    {
        return [
            'name' => $this->request->getPost('name'),
            'base_currency' => $this->request->getPost('base_currency'),
            'tax_number' => $this->request->getPost('tax_number'),
            'address' => $this->request->getPost('address'),
            'phone' => $this->request->getPost('phone'),
            'email' => $this->request->getPost('email'),
            'notify_before_days_default' => $this->request->getPost('notify_before_days_default') ?: 7,
            'is_active' => $this->request->getPost('is_active') ? 1 : 0,
        ];
    }
}
