<?php namespace App\Controllers\Api;
use App\Controllers\BaseApiController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Models\MenuModel;
use CodeIgniter\RESTful\ResourceController;

class MenuController extends BaseApiController
{
    public function getMenuList()
    {
        // $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 payload.');
            // }

            // Fetch departments
            $menuModel = new MenuModel();
            $menus = $menuModel->where('row_status', 1)->findAll();

            return $this->respond([
                'status' => 200,
                'message' => 'menus fetched successfully.',
                'data' => $menus
            ]);

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
   public function addMenu()
   {
        helper(['form']);

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

        // Validation rules
        $this->validate([
            'name'       => 'required|min_length[2]|max_length[255]',
            'parent_id'  => 'permit_empty|integer'
        ]);

        // 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.');
            }

            // Insert into DB
            $menuModel = new MenuModel();
            $insertData = [
                'name'        => $this->request->getPost('name'),
                'template'    => $this->request->getPost('template'),
                'parent_id'   => $this->request->getPost('parent_id') ?? 0,  // default to 0 = main menu
                'created_by'  => $userId,
                'row_status'  => 1,
                'created_at'  => date('Y-m-d H:i:s')
            ];

            if ($menuModel->insert($insertData)) {
                return $this->respond([
                    'status'  => true,
                    'message' => 'Menu added successfully.',
                ]);
            } else {
                return $this->fail('Failed to insert menu.');
            }

        } catch (\Exception $e) {
            log_message('error', 'JWT Decode/Add Menu Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
   }
   public function deleteMenu()
    {
        $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 = JWT::decode($token, new 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->fail('Invalid menu ID.');
            }

            $menuModel = new MenuModel();
            $existing = $menuModel->find($id);

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

            // Soft delete: just set row_status = 0
            $menuModel->update($id, ['row_status' => 0]);

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

        } catch (\Exception $e) {
            log_message('error', 'Delete Menu Error: ' . $e->getMessage());
            return $this->failUnauthorized('Invalid or expired token.');
        }
    }
    public function getMenuById()
    {
        $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 = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
            $userId = $decoded->user_id ?? null;

            $id = $this->request->getGet('id');

            if (!$id || !is_numeric($id)) {
                return $this->failValidationErrors('Valid ID is required.');
            }

            $menuModel = new MenuModel();
            $menu = $menuModel->find($id);

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

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

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

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

        // Validation rules
        $this->validate([
            'id'         => 'required|integer',
            'name'       => 'required|min_length[2]|max_length[255]',
            'parent_id'  => 'permit_empty|integer'
        ]);

        // 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.');
            }

            $menuModel = new MenuModel();

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

            // Check if menu exists
            $existingMenu = $menuModel->find($id);
            if (!$existingMenu) {
                return $this->failNotFound('Menu not found.');
            }

            $updateData = [
                'name'       => $this->request->getPost('name'),
                'template'    => $this->request->getPost('template'),
                'parent_id'  => $this->request->getPost('parent_id') ?? 0,
                'updated_by' => $userId,
                'updated_at' => date('Y-m-d H:i:s')
            ];

            if ($menuModel->update($id, $updateData)) {
                return $this->respond([
                    'status'  => true,
                    'message' => 'Menu updated successfully.'
                ]);
            } else {
                return $this->fail('Failed to update menu.');
            }

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

}