<?php

namespace App\Controllers\Api\V1;

use Exception;
use App\Controllers\BaseController;
use App\Models\InsuranceProductsModel;
use CodeIgniter\HTTP\ResponseInterface;

class PackagesController extends BaseController
{
    protected  $insuranceProductModel;
    public function __construct()
    {
        $this->insuranceProductModel = new InsuranceProductsModel();
    }
    public function packages()
    {
        try {
            $query = $this->webdocdb->table('InsuranceProducts')
                ->select('*')
                ->where('Packagetype', 'Zindagi')
                // ->orderBy('id', 'desc')
                ->get();
            $result = $query->getResultArray();
            return $this
                ->getApiResponse(
                    [
                        'statusCode' => 1,
                        'message' => "Packages information has been fetched successfully.",
                        'data' => $result,
                    ]
                );
        } catch (Exception $e) {
            return $this->getApiResponse(
                [
                    'statusCode' => 3,
                    'message' => $e->getMessage()
                ],
            );
        }
    }

    public function view()
    {
        try {
            $rules = [
                'package_id' => 'required',
            ];
            $errors = [
                'package_id' => [
                    'required' => 'Package id can not be empty.',
                ],
            ];
            $input = $this->getApiGetRequestInput($this->request);
            if (!$this->validateApiRequest($input, $rules, $errors)) {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 3,
                            'message' => array_values($this->validator->getErrors()),
                        ],
                    );
            }

            $result = $this->insuranceProductModel->select('*')
                ->where('id', $input['package_id'])->first();

            if (!$result) {
                return $this->getApiResponse([
                    'statusCode' => 3,
                    'message' => 'Package not found.',
                ]);
            } else {
                return $this
                    ->getApiResponse(
                        [
                            'statusCode' => 1,
                            'message' => "Package information has been fetched successfully.",
                            'data' => $result,
                        ]
                    );
            }
        } catch (Exception $e) {
            return $this->getApiResponse(
                [
                    'statusCode' => 3,
                    'message' => $e->getMessage()
                ],
            );
        }
    }

}
