<?php
session_start();
ob_start();
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Facebook;


require_once(__DIR__ . "/../../../adbcon.php");
require_once(__DIR__ . "/../../../vendor/autoload.php");
$result = [
    'status' => 0
];

$link = trim($_POST['post_link']);
$message = trim($_POST['post_message']) != "" ? trim($_POST['post_message']) : null;
$catdom_id = intval($_POST['catdom_id']);

$post_data = [
    'link' => $link
];
if($message != null) $post_data['message'] = $message;


// Get facebook account details
$q = "SELECT a.* FROM social_accounts a, social_domains d WHERE a.domain_id=d.id AND d.catdom_id='$catdom_id' AND a.social_network='facebook';";
$r = @mysql_query($q);
if($r && mysql_num_rows($r) == 1) {
    $row = mysql_fetch_assoc($r);

    $facebook_account = (object) unserialize(base64_decode($row['social_params']));

    //dd($facebook_account);

    try {
        $fb = new Facebook([
            'app_id' => $facebook_account->app_id,
            'app_secret' => $facebook_account->app_secret,
            'default_graph_version' => 'v3.1',
        ]);
        $fb->setDefaultAccessToken($facebook_account->access_token);


        try {
            $post = $fb->post('/' . $facebook_account->page_id . '/feed', $post_data);
            $post = $post->getGraphNode()->asArray();

            $result['status'] = 1;
            $result['post'] = $post;

        } catch (FacebookSDKException $e) {
            //dd($e); // handle exception
            $result['status'] = 0;
            $result['error'] = $e->getMessage();
        }



        //dd($accounts);

    }
    catch (FacebookSDKException $e) {
        //dd($e->getMessage());

        $result['status'] = 0;
        $result['error'] = $e->getMessage();
    }
}


//dd($result);

ob_end_clean();

echo json_encode($result);
exit;