<?php namespace App\Controllers\Api;
use App\Controllers\BaseApiController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

use App\Models\HomeServicesModel;
use App\Models\HomeAcademicModel;
use CodeIgniter\RESTful\ResourceController;

class HomeController extends BaseApiController
{
    public function getServices(){
        // $authHeader = $this->request->getHeaderLine('Authorization');

        // if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
        //     return $this->failUnauthorized('Token missing');
        // }

        // $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            // $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            // $userId = $decoded->user_id ?? null;

            $servicesModel = new \App\Models\HomeServicesModel();

            $services = $servicesModel
                        ->where('row_status', 1) // optional: only active records
                        ->orderBy('id', 'DESC')
                        ->first();

            return $this->respond([
                'status' => true,
                'data'   => $services ?? [] // return blank array if null
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function createServices()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $content = $this->request->getPost('content');

            if (empty($content)) {
                return $this->failValidationErrors('Content is required');
            }

            $model = new \App\Models\HomeServicesModel();

            $newId = $model->insert([
                'content'     => $content,
                'row_status'  => 1,
                'updated_at'  => date('Y-m-d H:i:s'),
                'updated_by'  => $userId,
            ]);

            if (!$newId) {
                return $this->failServerError('Failed to create service');
            }

            return $this->respond([
                'status'  => true,
                'message' => 'Service created successfully',
                'data'    => ['id' => $newId],
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateServices()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            if (empty($id)) {
                return $this->failValidationErrors('Service ID is required');
            }

            if (empty($content)) {
                return $this->failValidationErrors('Content is required');
            }

            $model = new \App\Models\HomeServicesModel();
            $service = $model->find($id);

            if (!$service || $service['row_status'] != 1) {
                return $this->failNotFound('Service not found');
            }

            $model->update($id, [
                'content'    => $content,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => $userId,
            ]);

            return $this->respond([
                'status'  => true,
                'message' => 'Service updated successfully',
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }

    public function getAcademicPrograms(){
        // $authHeader = $this->request->getHeaderLine('Authorization');

        // if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
        //     return $this->failUnauthorized('Token missing');
        // }

        // $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            // $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            // $userId = $decoded->user_id ?? null;

            $servicesModel = new \App\Models\HomeAcademicModel();

            $services = $servicesModel
                        ->where('row_status', 1) // optional: only active records
                        ->orderBy('id', 'DESC')
                        ->first();

            return $this->respond([
                'status' => true,
                'data'   => $services ?? [] // return blank array if null
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function createAcademicPrograms()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $content = $this->request->getPost('content');

            if (empty($content)) {
                return $this->failValidationErrors('Content is required');
            }

            $model = new \App\Models\HomeAcademicModel();

            $newId = $model->insert([
                'content'     => $content,
                'row_status'  => 1,
                'updated_at'  => date('Y-m-d H:i:s'),
                'updated_by'  => $userId,
            ]);

            if (!$newId) {
                return $this->failServerError('Failed to create service');
            }

            return $this->respond([
                'status'  => true,
                'message' => 'Service created successfully',
                'data'    => ['id' => $newId],
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function updateAcademicPrograms()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

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

            if (empty($id)) {
                return $this->failValidationErrors('Service ID is required');
            }

            if (empty($content)) {
                return $this->failValidationErrors('Content is required');
            }

            $model = new \App\Models\HomeAcademicModel();
            $service = $model->find($id);

            if (!$service || $service['row_status'] != 1) {
                return $this->failNotFound('Service not found');
            }

            $model->update($id, [
                'content'    => $content,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => $userId,
            ]);

            return $this->respond([
                'status'  => true,
                'message' => 'Service updated successfully',
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function getNoticesList()
    {
        // $authHeader = $this->request->getHeaderLine('Authorization');
        // if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
        //     return $this->failUnauthorized('Authorization token missing or invalid.');
        // }

        // $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            // $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            // $userId = $decoded->user_id ?? null;

            // if (!$userId) {
            //     return $this->failUnauthorized('Invalid token.');
            // }

            $rowStatus = $this->request->getGet('row_status') ?? 1;

            $noticesModel = new \App\Models\HomeNoticesModel();
            $notices = $noticesModel
                ->where('row_status', $rowStatus)
                ->orderBy('id', 'DESC')
                ->findAll();

            return $this->respond([
                'status' => 200,
                'data'   => $notices,
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Notices API Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }

    public function addNotices()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            // Validation rules
            $rules = [
                'type'    => 'required|in_list[Notice,Tender]',
                'content' => 'required',
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'status'  => false,
                    'message' => $this->validator->getErrors()
                ], 400);
            }

            $model = new \App\Models\HomeNoticesModel();

            $data = [
                'type'       => $this->request->getPost('type'),
                'content'    => $this->request->getPost('content'),
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => $userId,
                'row_status' => 1
            ];

            $model->save($data);

            return $this->respond([
                'status'  => true,
                'message' => 'Notice or tender added successfully.'
            ]);

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }

    public function getNoticeById()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Token missing');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $id = $this->request->getGet('id');
            if (!$id) {
                return $this->failValidationErrors('ID is required.');
            }

            $model = new \App\Models\HomeNoticesModel();
            $notice = $model->find($id);

            if (!$notice) {
                return $this->failNotFound('Notice not found.');
            }

            return $this->respond([
                'status' => true,
                'data'   => $notice
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }

    public function updateNotice()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $id = $this->request->getPost('id');
            if (!$id) {
                return $this->failValidationErrors('ID is required.');
            }

            // Validation rules
            $rules = [
                'type'    => 'required|in_list[Tender,Notice]',
                'content' => 'required',
            ];

            if (!$this->validate($rules)) {
                return $this->respond([
                    'status'  => false,
                    'message' => $this->validator->getErrors()
                ], 400);
            }

            $model = new \App\Models\HomeNoticesModel();
            $existing = $model->find($id);

            if (!$existing) {
                return $this->failNotFound('Notice not found.');
            }

            $data = [
                'type'       => $this->request->getPost('type'),
                'content'    => $this->request->getPost('content'),
                'updated_by' => $userId,
                'updated_at' => date('Y-m-d H:i:s'),
                'row_status' => 1
            ];

            $model->update($id, $data);

            return $this->respond([
                'status'  => true,
                'message' => 'Notice updated successfully.'
            ]);

        } catch (\Exception $e) {
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }

    public function deleteNotice()
    {
        $authHeader = $this->request->getHeaderLine('Authorization');

        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Missing token.');
        }

        $token = trim(str_replace('Bearer', '', $authHeader));

        try {
            $decoded = \Firebase\JWT\JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            if (!$userId) {
                return $this->failUnauthorized('Invalid token.');
            }

            $id = $this->request->getPost('id');
            if (!$id || !is_numeric($id)) {
                return $this->failValidationErrors('Invalid or missing notice ID.');
            }

            $model = new \App\Models\HomeNoticesModel();
            $existing = $model->find($id);

            if (!$existing) {
                return $this->failNotFound('Notice not found.');
            }

            // Soft delete
            $model->update($id, [
                'row_status' => 0,
                'updated_by' => $userId,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            return $this->respond([
                'status' => true,
                'message' => 'Notice deleted successfully.'
            ]);

        } catch (\Exception $e) {
            log_message('error', 'Delete Notice Error: ' . $e->getMessage());
            return $this->failServerError('Server error: ' . $e->getMessage());
        }
    }

     public function getBasicDetails(){
        try {

            $basicDetailsModel = new \App\Models\BasicDetailsModel();

            $details = $basicDetailsModel
                        ->where('row_status', 1) 
                        ->orderBy('id', 'DESC')
                        ->first();

            return $this->respond([
                'status' => true,
                'data'   => $details ?? []
            ]);

        } catch (\Exception $e) {
            return $this->failUnauthorized('Token error: ' . $e->getMessage());
        }
    }
    public function createBasicDetails()
    {
        try {
            helper(['form', 'url']);

            $validationRules = [
                'company_name'       => 'required|string',
                'email'              => 'permit_empty|valid_email',
                'mobile'             => 'permit_empty',
                'small_description'  => 'permit_empty',
                'long_description'   => 'permit_empty',
                'logo'               => 'permit_empty|is_image[logo]|max_size[logo,2048]'
            ];

            if (!$this->validate($validationRules)) {
                return $this->failValidationErrors($this->validator->getErrors());
            }

            $data = [
                'company_name'      => $this->request->getPost('company_name'),
                'email'             => $this->request->getPost('email'),
                'mobile'            => $this->request->getPost('mobile'),
                'small_description' => $this->request->getPost('small_description'),
                'long_description'  => $this->request->getPost('long_description'),
                'row_status'        => $this->request->getPost('row_status') ?? 1,
                'created_at'        => $this->request->getPost('created_at') ?? date('Y-m-d H:i:s'),
                'created_by'        => $this->request->getPost('created_by') ?? null,
                'updated_at'        => $this->request->getPost('updated_at') ?? date('Y-m-d H:i:s'),
                'updated_by'        => $this->request->getPost('updated_by') ?? null,
            ];

            $logo = $this->request->getFile('logo');
            if ($logo && $logo->isValid() && !$logo->hasMoved()) {
                $newName = uniqid() . '.' . $logo->getClientExtension();
                $logo->move(ROOTPATH . 'public/uploads/logo', $newName);
                $data['logo'] = $newName;
            }

            $model = new \App\Models\BasicDetailsModel();
            $model->insert($data);

            return $this->respond([
                'status'  => true,
                'message' => 'Company details created successfully.'
            ]);
        } catch (\Exception $e) {
            return $this->failServerError('Error: ' . $e->getMessage());
        }
    }
    public function updateBasicDetails()
    {
        try {
            helper(['form', 'url']);

            $id = $this->request->getPost('id');
            if (!$id) {
                return $this->failValidationErrors(['id' => 'ID is required']);
            }

            $model = new \App\Models\BasicDetailsModel();
            $existing = $model->find($id);
            if (!$existing) {
                return $this->failNotFound('Record not found');
            }

            $validationRules = [
                'company_name'      => 'required|string',
                'email'             => 'permit_empty|valid_email',
                'mobile'            => 'permit_empty',
                'small_description' => 'permit_empty',
                'long_description'  => 'permit_empty',
                'logo'              => 'permit_empty|is_image[logo]|max_size[logo,2048]'
            ];

            if (!$this->validate($validationRules)) {
                return $this->failValidationErrors($this->validator->getErrors());
            }

            $data = [
                'company_name'      => $this->request->getPost('company_name'),
                'email'             => $this->request->getPost('email'),
                'mobile'            => $this->request->getPost('mobile'),
                'small_description' => $this->request->getPost('small_description'),
                'long_description'  => $this->request->getPost('long_description'),
                'row_status'        => $this->request->getPost('row_status') ?? 1,
                'updated_at'        => date('Y-m-d H:i:s'),
                'updated_by'        => $this->request->getPost('updated_by') ?? null,
            ];

            $logo = $this->request->getFile('logo');
            if ($logo && $logo->isValid() && !$logo->hasMoved()) {
                $newName = uniqid() . '.' . $logo->getClientExtension();
                $logo->move(ROOTPATH . 'public/uploads/logo', $newName);
                $data['logo'] = $newName;

                // Optional: delete old logo if it exists
                if (!empty($existing['logo']) && file_exists(ROOTPATH . 'public/uploads/logo/' . $existing['logo'])) {
                    unlink(ROOTPATH . 'public/uploads/logo/' . $existing['logo']);
                }
            }

            $model->update($id, $data);

            return $this->respond([
                'status'  => true,
                'message' => 'Company details updated successfully.'
            ]);
        } catch (\Exception $e) {
            return $this->failServerError('Error: ' . $e->getMessage());
        }
    }








}
?>