<?php

namespace App\Models;

use CodeIgniter\Model;
use Exception;
use Config\Services;

class CompanyModel extends Model
{
    private $companyData = [];
    protected $baseUrl = 'http://localhost:3000/api/companies/';

    public function getToken()
    {
        $session = session();
        return $session->get('token');
    }


    public function login($email, $password)
    {
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->post($this->baseUrl . 'login', [
                'form_params' => [
                    'email' => $email,
                    'password' => $password
                ]
            ]);

            $result = json_decode($response->getBody());
            if (isset($result->token) && isset($result->roleId)) {
                return $result;
            } else {
                return false;
            }
        } catch (Exception $e) {
            // Handle exception
            return false;
        }
    }

    public function registerCompany($companyData)
    {
        $client = \Config\Services::curlrequest();

        try {
            $response = $client->post($this->baseUrl, [
                'form_params' => $companyData
            ]);

            return json_decode($response->getBody());
        } catch (Exception $e) {
            // Handle exception
            return false;
        }
    }

    public function getCompanyById($companyId)
    {
        $client = Services::curlrequest();
        $response = $client->get($this->baseUrl . $companyId);
        return json_decode($response->getBody());
    }

    public function updateCompany($companyId, $data)
    {
        $client = Services::curlrequest();
        $response = $client->put($this->baseUrl . $companyId, [
            'json' => $data
        ]);
        return json_decode($response->getBody());
    }

    public function uploadLogo($companyId, $file)
    {
        $client = Services::curlrequest();
        $formData = [
            'logo' => new \CURLFile($file->getRealPath(), $file->getMimeType(), $file->getName())
        ];

        $response = $client->put($this->baseUrl . $companyId, [
            'multipart' => $formData
        ]);

        return json_decode($response->getBody());
    }
    public function uploadAkta($companyId, $file)
    {
        $client = Services::curlrequest();
        $formData = [
            'akta' => new \CURLFile($file->getRealPath(), $file->getMimeType(), $file->getName())
        ];

        $response = $client->put($this->baseUrl . $companyId  . '/akta', [
            'multipart' => $formData
        ]);

        return json_decode($response->getBody());
    }

    public function deleteVacancyByCompany($companyId, $vacancyId)
    {
        $client = Services::curlrequest();
        $response = $client->delete($this->baseUrl . $companyId . '/vacancies/' . $vacancyId);
        return json_decode($response->getBody());
    }
}
