<?php

namespace App\Controllers;

use App\Models\PaymentMethodModel;

class Payment_Method extends BaseController
{
    public function index()
    {
        $model = new PaymentMethodModel();

        $data['paymentmethods'] = $model->whereIn('status', [1, 2])->orderBy('created_datetime', 'DESC')->findAll();

        return view('payment_method', $data);
    }

    public function save()
    { 
        $model = new PaymentMethodModel();

        $result = $model->save([
            'name' => $this->request->getPost('name'),
            'code' => strtoupper($this->request->getPost('code')),
            'description' => $this->request->getPost('description'),
            'status' => $this->request->getPost('status')
        ]);

        if ($result) {
            session()->setFlashdata(
                'success',
                'Payment Method saved successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to save Payment Method.'
            );
        }

        return redirect()->to('/paymentmethod');
    }

    public function get($id)
    {
        $model = new PaymentMethodModel();

        $data = $model->find($id);

        return $this->response->setJSON($data);
    }

    public function update()
    {
        $model = new PaymentMethodModel();

        $id = $this->request->getPost('updid');

        $result = $model->update($id, [
            'code' => strtoupper($this->request->getPost('updcode')),
            'name' => $this->request->getPost('updname'),
            'description' => $this->request->getPost('upddescription'),
            'status' => $this->request->getPost('updstatus'),
        ]);

        if ($result) {
            session()->setFlashdata(
                'success',
                'Payment Method updated successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to update Payment Method.'
            );
        }

        return redirect()->to('/paymentmethod');
    }

    public function delete()
    {
        $model = new PaymentMethodModel();

        $id = $this->request->getPost('delid');

        $result = $model->update($id, [
            'status' => 3
        ]);

        if ($result) {
            session()->setFlashdata(
                'success',
                'Payment Method deleted successfully.'
            );
        } else {
            session()->setFlashdata(
                'error',
                'Unable to delete Payment Method.'
            );
        }

        return redirect()->to('/paymentmethod');
    }
}