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

$postdownloaderId = $_GET['p'];
$storydownloaderId = $_GET['s'];

$resultnext = [];

$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' => 'codesazan'], 448);
    die;
}

try {
    $context = stream_context_create(['http'=>[ 'timeout' => 20]]);
    $endpoint = "https://api.fast-creat.ir/instagram";
    $key = '1734375276:yLUzZ3ahkr5jmc0@Api_ManagerRoBot';
        
    if(strpos($get_url, '/reel/') || strpos($get_url, '/p/')) // post or reels
    {
        $url = $endpoint . '?' . http_build_query(['apikey' => "$key", 'type' => 'post2' , 'link' => "$get_url"]);
        
        $end_url = file_get_contents($url, false, $context);
        if($end_url === false)
            throw new Exception("Cannot access '$url' to read contents.");
            
        if($test) {
            // echo($end_url);
            // die;
        }

        $serviceResultArray = json_decode($end_url,true);
    
        if($serviceResultArray['status'] != 200 || !isset($serviceResultArray['result']['medias'][0]['url']))
            throw new Exception("result: " . $end_url); 
        
        $resultnext = [
            'number'=> count($serviceResultArray['result']['medias']) -1
        ];
        
        $index = 0;
        foreach ($serviceResultArray['result']['medias'] as $storyItem)
            $resultnext[$index++] = [
                'link' => $storyItem['url'], 
                'caption' => $serviceResultArray['result']['caption']
            ];
        
        if($test) {
             var_dump($end_url);
             var_dump($resultnext);
             die;
        }

        echo json_encode(['ok' => 1, 'Results' =>$resultnext, 'api' => 'codesazan'], 448);
    }
    elseif(strpos($get_url, '/stories/'))
    {
        $url = $endpoint . '?' . http_build_query(['key' => "$key", 'type' => 'storydownloader' . $storydownloaderId , 'link' => "$get_url"]);
        
        $end_url = file_get_contents($url, false, $context);
        if($end_url === false)
            throw new Exception("Cannot access '$url' to read contents.");
            
        $serviceResultArray = json_decode($end_url,true);
    
        if($serviceResultArray['status'] != 200 || !isset($serviceResultArray['result']['medias']['url']))
            throw new Exception("result: " . $end_url); 
        
        $resultnext = [
                'number'=> 0,
                0 =>[
                    'link' => $serviceResultArray['result']['medias']['url'],
                    'caption' => ''
                ]
            ];
        
        if($test) {
             var_dump($resultnext);
             die;
        }

        echo json_encode(['ok' => 1, 'Results' =>$resultnext, 'api' => 'codesazan'], 448);
    }
    //elseif(strpos($get_url, '/s/'))  //highlight
    //{
        // $url = $endpoint . '?' . http_build_query(['key' => "$key", 'type' => 'postdownloader3', 'link' => "$get_url"]);
        
        // $end_url = file_get_contents($url, false, $context);
        // if($end_url === false)
        //     throw new Exception("Cannot access '$url' to read contents.");
            
        // if($test) {
        //      //var_dump($end_url);
        //      //die;
        // }
        // $serviceResultArray = json_decode($end_url,true);
    
        // if($serviceResultArray['success'] != 200 || !isset($serviceResultArray['result']['media']))
        //    throw new Exception("result: " . $end_url); 
        
        // $resultnext = [
        //         'number'=> 0,
        //         0 =>[
        //             'link' => $serviceResultArray['result']['media'],
        //             'caption' => ''
        //         ]
        //     ];
        
        // if($test) {
        //      var_dump($resultnext);
        //      die;
        // }

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