<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;
use App\Models\SupplierModel;

class SupplierController extends BaseController
{
    protected $model;

    public function __construct()
    {
        $this->model = new SupplierModel();
    }

    public function index()
    {
        $q = trim($this->request->getGet('q') ?? '');
        $builder = $this->model;
        if ($q !== '') {
            $builder = $builder->groupStart()
                ->like('name', $q)->orLike('email', $q)->orLike('phone', $q)
                ->groupEnd();
        }
        return view('inventory/suppliers_index', [
            'suppliers' => $builder->orderBy('name')->paginate(20),
            'pager'     => $this->model->pager,
            'q'         => $q,
        ]);
    }

    public function create()
    {
        return view('inventory/suppliers_form', [
            'title' => 'Add Supplier',
            'action' => site_url('inventory/suppliers/store'),
            'supplier' => null,
        ]);
    }

    public function store()
    {
        $data = $this->request->getPost(['name','email','phone','address','notes']);
        if (!$this->model->save($data)) {
            return redirect()->back()->withInput()->with('error', implode("\n", $this->model->errors()));
        }
        return redirect()->to(site_url('inventory/suppliers'))->with('success', 'Supplier saved.');
    }

    public function edit($id)
    {
        $s = $this->model->find($id);
        if (!$s) return redirect()->to('inventory/suppliers')->with('error', 'Not found.');
        return view('inventory/suppliers_form', [
            'title' => 'Edit Supplier',
            'action' => site_url('inventory/suppliers/update/'.$id),
            'supplier' => $s,
        ]);
    }

    public function update($id)
    {
        $data = $this->request->getPost(['name','email','phone','address','notes']);
        $data['id'] = $id;
        if (!$this->model->save($data)) {
            return redirect()->back()->withInput()->with('error', implode("\n", $this->model->errors()));
        }
        return redirect()->to(site_url('inventory/suppliers'))->with('success', 'Supplier updated.');
    }

    public function delete($id)
    {
        $this->model->delete($id);
        return redirect()->to(site_url('inventory/suppliers'))->with('success', 'Supplier deleted.');
    }
}
