<?php
namespace App\Controllers\PSI;

use App\Controllers\Controller;
use App\Models\PSI\Supplier;

/** 供应商管理（进出口/面辅料供应商） */
class SuppliersController extends Controller
{


    public function index()
    {
        $suppliers = (new Supplier())->all();
        return $this->renderSubsys('psi', 'psi/suppliers', ['suppliers' => $suppliers], \psi_nav(), 'suppliers');
    }

    public function create()
    {
        subsys_admin('psi') or \Core\App::forbidden('需要 PSI 管理员权限');
        return $this->renderSubsys('psi', 'psi/supplier_form', ['supplier' => null], \psi_nav(), 'suppliers');
    }

    public function store()
    {
        subsys_admin('psi') or \Core\App::forbidden('需要 PSI 管理员权限');
        if (!csrf_check()) return $this->redirect('PSI/suppliers');
        (new Supplier())->insert($this->collect());
        return $this->redirect('PSI/suppliers');
    }

    public function edit($id)
    {
        subsys_admin('psi') or \Core\App::forbidden('需要 PSI 管理员权限');
        $supplier = (new Supplier())->find($id);
        if (!$supplier) return $this->redirect('PSI/suppliers');
        return $this->renderSubsys('psi', 'psi/supplier_form', ['supplier' => $supplier], \psi_nav(), 'suppliers');
    }

    public function update($id)
    {
        subsys_admin('psi') or \Core\App::forbidden('需要 PSI 管理员权限');
        if (!csrf_check()) return $this->redirect('PSI/suppliers');
        $supplier = (new Supplier())->find($id);
        if (!$supplier) return $this->redirect('PSI/suppliers');
        (new Supplier())->update($id, $this->collect());
        return $this->redirect('PSI/suppliers');
    }

    public function destroy($id)
    {
        subsys_admin('psi') or \Core\App::forbidden('需要 PSI 管理员权限');
        (new Supplier())->delete($id);
        return $this->redirect('PSI/suppliers');
    }

    private function collect(): array
    {
        return [
            'name'       => trim($this->post('name')),
            'contact'    => trim($this->post('contact')),
            'phone'      => trim($this->post('phone')),
            'country'    => trim($this->post('country')),
            'type'       => trim($this->post('type')),
            'grade'      => trim($this->post('grade')),
            'ontime_rate'=> (float)$this->post('ontime_rate'),
            'qc_rate'    => (float)$this->post('qc_rate'),
            'remark'     => trim($this->post('remark')),
            'created_at' => date('Y-m-d'),
        ];
    }
}
