<?php

namespace App\Controllers\Common;

use App\Controllers\BaseController;

class MenuController extends BaseController
{
    public function index()
    {
        $session = session();

        $data['page_title'] = "Menu || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content="' . COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords">'
                        . '<meta content="School Management System, ' . COMPANY_FULL_NAME . ', Sketch Me Global" name="description">';

        $jwtToken = session('jwt_token');
        $userId = session('user_id');

        if (!$jwtToken || !$userId) {
            return $this->response->setJSON([
                'status' => 401,
                'message' => 'Unauthorized',
            ]);
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url().'api/menu/get-menu-list', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false 
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] == 200) {
                $data['menu'] = $apiResponse['data'] ?? [];
            } else {
                $data['menu'] = [];
                $data['error'] = $apiResponse['message'] ?? 'Unable to fetch menu list';
            }

        } catch (\Exception $e) {
            log_message('error', 'menu API Call Failed: ' . $e->getMessage());
            $data['menu'] = [];
            $data['error'] = 'Something went wrong while fetching menu.';
        }

        return view('menu/index', $data);
    }
    public function addMenu(){
        
        $session = session();
        $jwtToken = session('jwt_token');
        $client = \Config\Services::curlrequest();
        $response = $client->get(base_url().'api/menu/get-menu-list', [
            'headers' => [
                'Authorization' => 'Bearer ' . $jwtToken,
                'Accept'        => 'application/json',
            ],
            'query' => [
                'row_status' => 1
            ],
            'verify' => false 
        ]);

        $apiResponse = json_decode($response->getBody(), true);

        $data['menus'] = $apiResponse['data'] ?? [];
        
        $data['page_title'] = "Menu || " . COMPANY_SHORT_NAME;
        $data['meta_tag'] = '<meta content='. COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords"><meta content=School Management System,'.COMPANY_FULL_NAME.'", Sketch Me Global" name="description">';
        return view('menu/add', $data);
        
    }
    public function deleteMenu($id)
    {
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized action.');
        }

        try {
            $client = \Config\Services::curlrequest();
            $response = $client->post(base_url() . 'api/menu/delete-menu', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'form_params' => [
                    'id' => $id
                ],
                'verify' => false // skip SSL check on local dev
            ]);

            $apiResponse = json_decode($response->getBody(), true);

            if (isset($apiResponse['status']) && $apiResponse['status'] === true) {
                return redirect()->to(base_url('backdesk/menu/index'))->with('success', $apiResponse['message'] ?? 'Menu deleted successfully.');
            } else {
                return redirect()->back()->with('error', $apiResponse['message'] ?? 'Failed to delete menu.');
            }

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Exception: ' . $e->getMessage());
        }
    }
    public function editMenu($id)
    {
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId   = $session->get('user_id');

        // Step 1: Check auth
        if (!$jwtToken || !$userId) {
            return redirect()->back()->with('error', 'Unauthorized access.');
        }

        try {
            $client = \Config\Services::curlrequest();

            // Step 2: Get single menu by ID
            $responseMenu = $client->get(base_url('api/menu/get-menu-by-id'), [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id
                ],
                'verify' => false
            ]);

            $menuData = json_decode($responseMenu->getBody(), true);

            if (!isset($menuData['status']) || $menuData['status'] !== true) {
                return redirect()->back()->with('error', 'Menu not found.');
            }

            // Step 3: Get full menu list (to show in parent select dropdown)
            $responseList = $client->get(base_url('api/menu/get-menu-list'), [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'row_status' => 1
                ],
                'verify' => false
            ]);

            $allMenus = json_decode($responseList->getBody(), true);

            // Step 4: Prepare data for the edit view
            $data = [
                'page_title'  => "Edit Menu || " . COMPANY_SHORT_NAME,
                'meta_tag'    => '<meta content="' . COMPANY_FULL_NAME . ', Sketch Me Global" name="keywords">' .
                                '<meta content="School Management System, ' . COMPANY_FULL_NAME . ', Sketch Me Global" name="description">',
                'menu'        => $menuData['data'],
                'menu_list'   => $allMenus['data'] ?? []
            ];

            return view('menu/edit', $data);

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'API error: ' . $e->getMessage());
        }
    }
   




}