<?php

namespace App\Http\Controllers\api\v1;

use App\Http\Controllers\BaseController;

use App\Modules\Bookings\Onsite;
use App\Modules\Bookings\Task;
use Illuminate\Support\Facades\Response;

class jophielwikiControllerRESTv1 extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function content($id)
    {
            $ch = curl_init();
            $task = Task::where('id',$id)->first();
            
            if (!$task) {
                return ['error' => 'Task not found'];
            }
            
            $task->load('client');
            
            if (!$task->client || !$task->client->Haniel_ID) {
                return ['error' => 'Client or Haniel ID not found'];
            }
            
            $hid = $task->client->Haniel_ID;

            curl_setopt($ch, CURLOPT_URL, config('wiki.url')."/rest/api/content/$hid/child/page");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

            $header = array();
            $header[] = 'Content-length: 0';
            $header[] = 'Content-type: application/json';
            $username = 'seraph_integration';
            $password = 'may11day';
            
            curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
            curl_setopt($ch, CURLOPT_HTTPHEADER,$header);

            
            $head = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode != 200) {
                return ['error' => 'Wiki API returned error code: ' . $httpCode];
            }
            
            $decoded = json_decode($head, true);
            
            if (!$decoded || !isset($decoded['results']) || !is_array($decoded['results'])) {
                return ['error' => 'Invalid response from wiki API'];
            }
            
            $output = [];
            foreach ($decoded['results'] as $results){
               if (isset($results['_links']['webui'])) {
                   array_push($output, config('wiki.url') . $results['_links']['webui']);
               }
            }
            return $output;
    }
}
