<?php

namespace App\Controllers\Common;

use App\Controllers\BaseController;

class PageMediaController extends BaseController
{
    public function index()
    {
        $session = session();
        $jwtToken = $session->get('jwt_token');
        $userId = $session->get('user_id');

        if (!$jwtToken || !$userId) {
            return redirect()->to(base_url('login'))->with('error', 'Unauthorized access.');
        }

        return view('interpages/page_media/index', [
            'page_title' => "Page Media || " . COMPANY_SHORT_NAME,
            'meta_tag'   => '<meta content="' . COMPANY_FULL_NAME . '" name="keywords">',
        ]);
    }

    public function addMedia()
    {
        $session = session();
        $jwtToken = $session->get('jwt_token');

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

        // Fetch menu list to show in dropdown
        try {
            $client = \Config\Services::curlrequest();
            $response = $client->get(base_url('api/menu/get-menu-list'), [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'verify' => false,
            ]);
            $apiResponse = json_decode($response->getBody(), true);
            $menus = $apiResponse['data'] ?? [];
        } catch (\Exception $e) {
            $menus = [];
        }

        return view('interpages/page_media/add', [
            'menus'      => $menus,
            'page_title' => "Add Page Media || " . COMPANY_SHORT_NAME,
            'meta_tag'   => '<meta content="' . COMPANY_FULL_NAME . '" name="keywords">',
        ]);
    }

   public function editMedia($id)
    {
        $session = session();
        $jwtToken = $session->get('jwt_token');

        // Ensure user is authenticated
        if (!$jwtToken) {
            return redirect()->to(base_url('login'))->with('error', 'Unauthorized access. Please login again.');
        }

        try {
            $client = \Config\Services::curlrequest();
            
            // Step 1: Get Media by ID
            $mediaResponse = $client->get(base_url('api/page-media/get-media-by-id'), [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'query' => [
                    'id' => $id,
                ],
                'verify' => false, // Skip SSL check in local dev
            ]);

            $mediaData = json_decode($mediaResponse->getBody(), true);
            

            if (!isset($mediaData['status']) || $mediaData['status'] !== true || empty($mediaData['data'])) {
                return redirect()->back()->with('error', 'Failed to fetch media details.');
            }

            // Step 2: Get Menu List
            $menuResponse = $client->get(base_url('api/menu/get-menu-list'), [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'verify' => false,
            ]);

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

            // Prepare view
            return view('interpages/page_media/edit', [
                'media'       => $mediaData['data'] ?? [],
                'menus'       => $menuData['data'] ?? [],
                'page_title'  => 'Edit Page Media || ' . COMPANY_SHORT_NAME,
                'meta_tag'    => '<meta content="' . COMPANY_FULL_NAME . '" name="keywords">',
            ]);

        } catch (\Exception $e) {
            log_message('error', 'EditMedia Exception: ' . $e->getMessage());
            return redirect()->back()->with('error', 'Error fetching media data: ' . $e->getMessage());
        }
    }


    public function deleteMedia($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/page-media/delete-media', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $jwtToken,
                    'Accept'        => 'application/json',
                ],
                'form_params' => [
                    'id' => $id
                ],
                'verify' => false // useful for skipping SSL issues on localhost
            ]);

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

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

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

}
