<?php defined('BASEPATH') OR exit('No direct script access allowed');

define('YT_CACHE_DIR', APPPATH . 'cache/youtube/');
define('YT_CACHE_TTL', 3600);

class Youtube extends CI_Controller
{
    private $is_admin = false;
    private $user_id  = 0;
    private $api_key  = '';

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('authorization');
        check_login();
        $this->load->model('Pengaturan_model');

        $this->user_id  = (int) $this->session->userdata('user_id');
        $this->is_admin = is_admin();

        // Ambil API key dari tabel pengaturan — tidak perlu hardcode lagi
        $p = $this->Pengaturan_model->get();
        $this->api_key = trim($p->youtube_api_key ?? '');

        if (!is_dir(YT_CACHE_DIR)) mkdir(YT_CACHE_DIR, 0755, true);
    }

    public function index()
    {
        $data['title']           = 'Cari Video';
        $data['is_admin']        = $this->is_admin;
        $data['keyword']         = $this->input->get('q') ?: '';
        $data['results']         = [];
        $data['error']           = '';
        $data['next_page_token'] = '';
        $data['prev_page_token'] = '';
        $data['total_results']   = 0;
        $data['api_configured']  = !empty($this->api_key);

        $q = trim($data['keyword']);
        if ($q !== '') {
            if (empty($this->api_key)) {
                $data['error'] = 'YouTube API Key belum diatur. Silakan isi di <a href="'.base_url('pengaturan').'">Pengaturan</a>.';
            } else {
                $page_token = $this->input->get('page') ?: '';
                $res = $this->_search($q, $page_token);
                if ($res['ok']) {
                    $data['results']         = $res['items'];
                    $data['next_page_token'] = $res['nextPageToken'] ?? '';
                    $data['prev_page_token'] = $res['prevPageToken'] ?? '';
                    $data['total_results']   = $res['totalResults'] ?? 0;
                } else {
                    $data['error'] = $res['msg'];
                }
            }
        }

        $this->load->view('templates/header', $data);
        $this->load->view('video/index', $data);
        $this->load->view('templates/footer');
    }

    public function ajax_search()
    {
        header('Content-Type: application/json');
        if (empty($this->api_key)) {
            echo json_encode(['ok' => false, 'msg' => 'API Key belum diatur']); return;
        }
        $q = trim($this->input->post('q') ?: $this->input->get('q') ?: '');
        if (!$q) { echo json_encode(['ok' => false, 'msg' => 'Keyword kosong']); return; }
        echo json_encode($this->_search($q, '', 8));
    }

    public function ajax_detail()
    {
        header('Content-Type: application/json');
        if (empty($this->api_key)) {
            echo json_encode(['ok' => false, 'msg' => 'API Key belum diatur']); return;
        }
        $video_id = preg_replace('/[^a-zA-Z0-9_\-]/', '', $this->input->post('video_id') ?: '');
        if (!$video_id) { echo json_encode(['ok' => false, 'msg' => 'Video ID tidak valid']); return; }

        $cached = $this->_cache_get('detail_' . $video_id);
        if ($cached) { echo json_encode(['ok' => true, 'data' => $cached]); return; }

        $url = 'https://www.googleapis.com/youtube/v3/videos?' . http_build_query([
            'part' => 'snippet,statistics,contentDetails',
            'id'   => $video_id,
            'key'  => $this->api_key,
        ]);

        $res = $this->_curl($url);
        if (!$res['ok']) { echo json_encode($res); return; }

        $items = $res['data']['items'] ?? [];
        if (empty($items)) { echo json_encode(['ok' => false, 'msg' => 'Video tidak ditemukan']); return; }

        $item = $items[0];
        $data = [
            'video_id'    => $video_id,
            'title'       => $item['snippet']['title'] ?? '',
            'channel'     => $item['snippet']['channelTitle'] ?? '',
            'description' => $item['snippet']['description'] ?? '',
            'published'   => $item['snippet']['publishedAt'] ?? '',
            'thumbnail'   => $item['snippet']['thumbnails']['high']['url']
                          ?? $item['snippet']['thumbnails']['default']['url'] ?? '',
            'view_count'  => number_format((int)($item['statistics']['viewCount'] ?? 0)),
            'like_count'  => number_format((int)($item['statistics']['likeCount'] ?? 0)),
            'duration'    => $this->_parse_duration($item['contentDetails']['duration'] ?? ''),
            'embed_url'   => 'https://www.youtube.com/embed/' . $video_id,
            'watch_url'   => 'https://www.youtube.com/watch?v=' . $video_id,
        ];

        $this->_cache_set('detail_' . $video_id, $data);
        echo json_encode(['ok' => true, 'data' => $data]);
    }

    private function _search($keyword, $page_token = '', $max_results = 12)
    {
        $cache_key = 'search_' . md5($keyword . '_' . $page_token . '_' . $max_results);
        $cached    = $this->_cache_get($cache_key);
        if ($cached) return $cached;

        $params = [
            'part'              => 'snippet',
            'q'                 => $keyword,
            'type'              => 'video',
            'maxResults'        => $max_results,
            'key'               => $this->api_key,
            'safeSearch'        => 'moderate',
            'relevanceLanguage' => 'id',
        ];
        if ($page_token) $params['pageToken'] = $page_token;

        $res = $this->_curl('https://www.googleapis.com/youtube/v3/search?' . http_build_query($params));
        if (!$res['ok']) return $res;

        $raw   = $res['data'];
        $items = [];
        foreach (($raw['items'] ?? []) as $it) {
            $vid  = $it['id']['videoId'] ?? '';
            $snip = $it['snippet'] ?? [];
            if (!$vid) continue;
            $items[] = [
                'video_id'    => $vid,
                'title'       => $snip['title'] ?? '',
                'channel'     => $snip['channelTitle'] ?? '',
                'description' => $snip['description'] ?? '',
                'published'   => $snip['publishedAt'] ?? '',
                'thumbnail'   => $snip['thumbnails']['medium']['url'] ?? $snip['thumbnails']['default']['url'] ?? '',
                'watch_url'   => 'https://www.youtube.com/watch?v=' . $vid,
                'embed_url'   => 'https://www.youtube.com/embed/' . $vid,
            ];
        }

        $result = [
            'ok'            => true,
            'items'         => $items,
            'nextPageToken' => $raw['nextPageToken'] ?? '',
            'prevPageToken' => $raw['prevPageToken'] ?? '',
            'totalResults'  => $raw['pageInfo']['totalResults'] ?? 0,
        ];
        $this->_cache_set($cache_key, $result);
        return $result;
    }

    private function _curl($url)
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT        => 10,
            CURLOPT_USERAGENT      => 'RT-App/1.0',
        ]);
        $res  = curl_exec($ch);
        $err  = curl_error($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // curl_close($ch);

        if ($err)          return ['ok' => false, 'msg' => 'cURL error: ' . $err];
        if ($code !== 200) {
            $body = json_decode($res, true);
            return ['ok' => false, 'msg' => $body['error']['message'] ?? 'HTTP ' . $code];
        }
        $data = json_decode($res, true);
        return $data ? ['ok' => true, 'data' => $data] : ['ok' => false, 'msg' => 'Response tidak valid'];
    }

    private function _cache_get($key)
    {
        $f = YT_CACHE_DIR . md5($key) . '.json';
        if (!file_exists($f) || (time() - filemtime($f)) > YT_CACHE_TTL) return null;
        return json_decode(file_get_contents($f), true) ?: null;
    }

    private function _cache_set($key, $data)
    {
        file_put_contents(YT_CACHE_DIR . md5($key) . '.json', json_encode($data));
    }

    private function _parse_duration($iso)
    {
        if (!$iso) return '';
        preg_match('/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/', $iso, $m);
        $h = (int)($m[1] ?? 0); $i = (int)($m[2] ?? 0); $s = (int)($m[3] ?? 0);
        return $h > 0 ? sprintf('%d:%02d:%02d', $h, $i, $s) : sprintf('%d:%02d', $i, $s);
    }
}