<?php namespace App\Controllers\Api;

use App\Controllers\BaseApiController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Models\PageContentsModel;
use CodeIgniter\HTTP\ResponseInterface;

class PageContentsController extends BaseApiController
{
   public function addOrUpdate()
    {
        helper(['form', 'filesystem']); // Include filesystem for file handling

        if (!$this->request->is('post')) {
            return $this->fail('Invalid request method. Only POST allowed.', 405);
        }

        // JWT Auth
        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

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

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

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

            // Validate required fields
            $validationRules = [
                'menu_id'    => 'required|integer',
                'submenu_id' => 'required|integer',
            ];

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

            $menuId    = $this->request->getPost('menu_id');
            $submenuId = $this->request->getPost('submenu_id');

            $pagesModel = new PageContentsModel();

            // Check existing record
            $existing = $pagesModel
                        ->where('menu_id', $menuId)
                        ->where('subamenu_id', $submenuId)
                        ->where('row_status', 1)
                        ->first();

            $data = [
                'menu_id'     => $menuId,
                'subamenu_id' => $submenuId,
                'section1'    => $this->request->getPost('section1'),
                'section2'    => $this->request->getPost('section2'),
                'section3'    => $this->request->getPost('section3'),
                'section4'    => $this->request->getPost('section4'),
                'section5'    => $this->request->getPost('section5'),
                'row_status'  => 1,
            ];

            $bannerFile = $this->request->getFile('banner_image');
            if ($bannerFile && $bannerFile->isValid() && !$bannerFile->hasMoved()) {
                $newName = uniqid('banner_', true) . '.' . $bannerFile->getClientExtension();
                $uploadPath = ROOTPATH . 'public/uploads/page_banners/';

                // Create directory if it doesn't exist
                if (!is_dir($uploadPath)) {
                    mkdir($uploadPath, 0777, true);
                }

                $bannerFile->move($uploadPath, $newName);
                $data['banner_image'] = $newName;
            }

            if ($existing) {
                // Update
                $data['updated_by'] = $userId;
                $data['updated_at'] = date('Y-m-d H:i:s');

                $pagesModel->update($existing['id'], $data);

                return $this->respond([
                    'status'  => true,
                    'message' => 'Page content updated successfully.',
                ], ResponseInterface::HTTP_OK);

            } else {
                // Insert
                $data['created_by'] = $userId;
                $data['created_at'] = date('Y-m-d H:i:s');

                $pagesModel->insert($data);

                return $this->respond([
                    'status'  => true,
                    'message' => 'Page content created successfully.',
                ], ResponseInterface::HTTP_CREATED);
            }

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode Error in Page Content Save/Update: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }

    public function getByMenuSubmenu()
    {
        $menuId    = $this->request->getGet('menu_id');
        $submenuId = $this->request->getGet('submenu_id');

        $authHeader = $this->request->getHeaderLine('Authorization');
        if (!$authHeader || !str_starts_with($authHeader, 'Bearer ')) {
            return $this->failUnauthorized('Authorization token missing.');
        }

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

        try {
            $decoded = JWT::decode($token, new \Firebase\JWT\Key(getenv('JWT_SECRET'), 'HS256'));

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

            $existing = $model->where([
                'menu_id'     => $menuId,
                'subamenu_id' => $submenuId,
                'row_status'  => 1
            ])->first();

            if ($existing) {
                return $this->respond([
                    'status' => true,
                    'data'   => $existing
                ]);
            } else {
                return $this->respond([
                    'status' => false,
                    'message' => 'No content found for this menu/submenu.'
                ]);
            }

        } catch (\Exception $e) {
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getPageData()
    {
        $id = $this->request->getGet('id');
    
        if (!$id) {
            return $this->respond([
                'status' => false,
                'message' => 'id is required.'
            ], 400);
        }

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

        $page = $model->where('subamenu_id', $id)
                    ->where('row_status', 1)
                    ->first();

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


}
