<?php
error_reporting(0);
header('Content-Type: application/json;');
$test = $_GET['test'] == 1;

$get_url = $_GET['url'];
if ($get_url == null) {
    $print_false_xd = array();
    $print_false_xd['res']['text']= "لطفا لینک پست خودرا بگذارید مانند نمونه instadw.php?url=https://www.instagram.com/p/CroXqJMI104/?igshid=YmMyMTA2M2Y=";
    echo json_encode(['ok' => -1, 'Results' =>$print_false_xd, 'api' => 'oneapi'], 448);
    die;
}

try {
    $sex_ut = "https://one-api.ir/instagram/";

    // if(strpos($get_url, '/reel/'))
    // {
    //     $ch = curl_init($sex_ut);
    //     curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36");
    //     curl_setopt($ch, CURLOPT_POST, true);
    //     curl_setopt($ch, CURLOPT_POSTFIELDS, ['token' => '947528:64cac7a629424', 'action' => 'reel', 'link'=>"$get_url", 'userinfo' => false]);
    //     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    //     curl_setopt($ch, CURLOPT_HEADER, FALSE);
    //     curl_setopt($ch,CURLOPT_NOBODY,FALSE);
    //     curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
    //     curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
    //     curl_setopt($ch,CURLOPT_AUTOREFERER,1);
    //     curl_setopt($ch,CURLOPT_ENCODING, 'UTF-8');
    //     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //     $end_url= curl_exec($ch);
    //     curl_close($ch);

    //     $serviceResultArray = json_decode($end_url,true); 
        
    //     if($test) {
    //          var_dump($get_url);
    //          var_dump($serviceResultArray);
    //          die;
    //     }
        
    //     if($serviceResultArray['status'] != 200)
    //         throw new Exception("Cannot access '$url' to read contents.");

    //     $resultnext = [
    //         'number'=> 0,
    //         0 =>[
    //             'link' => $serviceResultArray['result']['media'],
    //             'caption' => $serviceResultArray['result']['caption']
    //         ]
    //     ];

    //     echo json_encode(['ok' => 1,  'Results' =>$resultnext, 'api' => 'oneapi'], 448);
    // }
    // else
    if(strpos($get_url, '/stories/'))
    {
        $usernameFromLink = explode('/', $get_url);
        $url = 'https://api.one-api.ir/instagram/v1/user/?username=' . $usernameFromLink[4];
        $headers = 
        [
            "accept: application/json",
            "one-api-token: 947528:64cac7a629424"
        ];
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $response = curl_exec($ch);
        if (curl_errno($ch)) 
        {
            curl_close($ch);
            return null;
        }
        curl_close($ch);
        $serviceResultArray = json_decode($response, true);

        if($serviceResultArray['status'] != 200)
            throw new Exception("Cannot access '$url' to read contents.");
            
        $id = $serviceResultArray['result']['id'];

        $url = 'https://api.one-api.ir/instagram/v1/user/stories/?id=' . $id . '&username=' . $usernameFromLink;
        $headers = 
        [
            "accept: application/json",
            "one-api-token: 947528:64cac7a629424"
        ];
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $response = curl_exec($ch);
        if (curl_errno($ch)) 
        {
            curl_close($ch);
            return null;
        }
        curl_close($ch);
        $serviceResultArray = json_decode($response, true);

        if($serviceResultArray['status'] != 200)
            throw new Exception("Cannot access '$url' to read contents.");

        $resultnext = array();
        $resultnext['number']= count($serviceResultArray['result']) -1;

        $index = 0;
        foreach ($serviceResultArray['result'] as $storyItem)
            $resultnext[$index++] = ['link' => $storyItem['url'], 'caption' => ''];

        echo json_encode(['ok' => 1,  'Results' =>$resultnext, 'api' => 'oneapi'], 448);

    }
    elseif(strpos($get_url, '/p/') or strpos($get_url, '/reel/'))  //post and reel
    {
        $code = explode('/', $get_url);
        if (in_array('share', $code) && in_array('reel', $code)) $shortcode = '?share=' . $code[5];
        elseif (in_array('reel', $code) && !in_array('share', $code)) $shortcode = '?shortcode=' . $code[4];
        elseif (in_array('share', $code) && !in_array('reel', $code)) $shortcode = '?share=' . $code[4];
        else $shortcode = '?shortcode=' . $code[4];
        $url = 'https://api.one-api.ir/instagram/v1/post/'. $shortcode;
        $headers = 
        [
            "accept: application/json",
            "one-api-token: 947528:64cac7a629424"
        ];
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $response = curl_exec($ch);
        if (curl_errno($ch)) 
        {
            curl_close($ch);
            return null;
        }
        curl_close($ch);
        $serviceResultArray = json_decode($response, true);
        
        if($serviceResultArray['status'] != 200)
            throw new Exception("Cannot access '$url' to read contents.");

        $resultnext = array();
        $resultnext['number']= count($serviceResultArray['result']['media']) -1;

        $index = 0;
        foreach ($serviceResultArray['result']['media'] as $media)
            $resultnext[$index++] = ['link' => $media['url'], 'caption' => ''];

        $resultnext[$resultnext['number']]['caption'] = $serviceResultArray['result']['caption'];

        echo json_encode(['ok' => 1, 'Results' =>$resultnext, 'api' => 'oneapi'], 448);
    }
    elseif(strpos($get_url, '/s/'))  //highlight
    {
        $highlightId = base64_decode(substr(parse_url($get_url, PHP_URL_PATH), 3));
        $url = 'https://api.one-api.ir/instagram/v1/highlight/?id=' . $highlightId;
        $headers = 
        [
            "accept: application/json",
            "one-api-token: 947528:64cac7a629424"
        ];
    
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        $response = curl_exec($ch);
        if (curl_errno($ch)) 
        {
            curl_close($ch);
            return null;
        }
        curl_close($ch);
        $serviceResultArray = json_decode($response, true);

        if($serviceResultArray['status'] != 200)
            throw new Exception("Cannot access '$url' to read contents.");

        $resultnext = array();
        $resultnext['number']= count($serviceResultArray['result']) -1;

        $index = 0;
        foreach ($serviceResultArray['result'] as $highlightItem)
            $resultnext[$index++] = ['link' => $highlightItem['url'], 'caption' => ''];

        echo json_encode(['ok' => 1, 'Results' =>$resultnext, 'api' => 'oneapi'], 448);
    }
    
    else
        echo json_encode(['ok' => -1, 'Results' =>$print_false_xd, 'api' => 'oneapi'], 448);
}
catch (Exception $ex) {
    $print_false_xd = array();
    $print_false_xd['res']['text'] = "code:" . $ex->getCode() . " - Message:" . $ex->getMessage();
    echo json_encode(['ok' => 0, 'Results' =>$print_false_xd, 'api' => 'oneapi'], 448);
    exit;
}