<?php
require_once('config.php');
require_once('inc/user-validation.php');
header('Content-Type: application/json; charset=utf-8');

function out($ok, $msg, $extra=[]) {
    echo json_encode(array_merge(['success'=>$ok, 'message'=>$msg], $extra), JSON_UNESCAPED_UNICODE);
    exit;
}

function fb_pc_clean_text($value) {
    $value = is_string($value) ? $value : '';
    return preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $value);
}

function fb_pc_graph_post($url, $fields, $timeout=45) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    $res  = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);
    return [$http, $res, $err, json_decode($res, true)];
}

function fb_pc_graph_get($url, $timeout=20) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    $res  = curl_exec($ch);
    $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);
    return [$http, $res, $err, json_decode($res, true)];
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') out(false, 'Invalid request method.');

if (($advancenews['FB_AUTO_SHARE_ENABLED'] ?? 'off') !== 'on') {
    out(false, 'Facebook Auto-Share বন্ধ আছে। Admin → Photo Card → Facebook Auto Sharing থেকে চালু করুন।');
}

$post_id  = intval($_POST['post_id'] ?? 0);
$img_b64  = $_POST['image_data'] ?? '';
if (!$post_id || !$img_b64) out(false, 'Post ID বা Image data পাওয়া যায়নি।');

$the_post = isArticles($post_id, 'id');
if (!$the_post) out(false, 'পোস্টটি খুঁজে পাওয়া যায়নি।');

$page_id = $advancenews['FB_PAGE_ID']    ?? '';
$token   = $advancenews['FB_PAGE_TOKEN'] ?? '';
$ver     = $advancenews['FB_GRAPH_VERSION'] ?? 'v23.0';
if (!$page_id || !$token) out(false, 'Page ID বা Access Token সেট করা নেই।');

// Token must be a Page Access Token with modern Page permissions.
// pages_manage_posts       -> create wall post / photo
// pages_read_engagement    -> read engagement
// pages_manage_engagement  -> Page auto first-comment on its own post (fixes #200)
$app_id = $advancenews['FB_APP_ID'] ?? '';
$app_secret = $advancenews['FB_APP_SECRET'] ?? '';
$token_scopes = [];
if ($app_id && $app_secret) {
    $debug_url = "https://graph.facebook.com/{$ver}/debug_token?input_token=" . urlencode($token) . "&access_token=" . urlencode($app_id.'|'.$app_secret);
    [$dhttp, $dres, $derr, $debug] = fb_pc_graph_get($debug_url);
    if ($dhttp === 200 && !empty($debug['data'])) {
        $token_scopes = $debug['data']['scopes'] ?? [];
        $required = ['pages_manage_posts', 'pages_read_engagement', 'pages_manage_engagement'];
        $missing  = array_values(array_diff($required, $token_scopes));
        if (!empty($missing)) {
            out(false, 'এই Page Access Token-এ missing permission: '.implode(', ', $missing).'. Graph API Explorer-এ গিয়ে Page Token-এ pages_manage_posts + pages_read_engagement + pages_manage_engagement তিনটি select করে নতুন token নিন। (publish_actions deprecated)।');
        }
        if (in_array('publish_actions', $token_scopes, true)) {
            out(false, 'Token-এ পুরনো publish_actions দিয়ে তৈরি। Facebook publish_actions বন্ধ করেছে। নতুন Page Access Token বানান যেখানে pages_manage_posts ও pages_manage_engagement থাকবে।');
        }
    }
}
// ---- 1) Save photocard image to uploads/photocard-shares/ ----
$share_dir = dirname(__DIR__) . '/uploads/photocard-shares';
if (!is_dir($share_dir)) @mkdir($share_dir, 0755, true);

if (preg_match('/^data:image\/(png|jpe?g);base64,(.+)$/', $img_b64, $m)) {
    $ext = ($m[1]==='png') ? 'png' : 'jpg';
    $raw = base64_decode($m[2]);
} else {
    out(false, 'Image data format ভুল।');
}
if (!$raw) out(false, 'Image decode করা যায়নি।');

$filename = 'photocard-' . $post_id . '-' . time() . '.' . $ext;
$filepath = $share_dir . '/' . $filename;
if (!file_put_contents($filepath, $raw)) out(false, 'সার্ভারে image সেভ করা যায়নি (folder permission চেক করুন)।');

// === AUTO CLEANUP ===
// Share সফল হোক বা ব্যর্থ, response যাওয়ার পর ফাইল সার্ভার থেকে মুছে যাবে।
// এর ফলে uploads/photocard-shares/ ফোল্ডার কখনো বড় হয়ে hosting space খাবে না।
register_shutdown_function(function() use ($filepath, $share_dir) {
    if (is_file($filepath)) { @unlink($filepath); }
    // Failsafe sweep: ৫ মিনিটের বেশি পুরনো leftover ফাইল মুছে দাও
    if (is_dir($share_dir)) {
        $now = time();
        foreach (glob($share_dir.'/photocard-*.{png,jpg,jpeg}', GLOB_BRACE) ?: [] as $f) {
            if (is_file($f) && ($now - @filemtime($f)) > 300) { @unlink($f); }
        }
    }
});

// Public URL
$public_url = rtrim($site_domain, '/') . '/uploads/photocard-shares/' . $filename;

// ---- 2) Build caption & comment from template ----
$post_link = articleLink($the_post['PostId'], 'url');
$shortcodes = [
    '{title}'    => $the_post['PostTitle'],
    '{category}' => articleCategory($the_post['PostId'], 'name'),
    '{date}'     => dokanDate($the_post['PostDatePublic']),
    '{link}'     => $post_link,
];
$caption_tpl = $advancenews['FB_CAPTION_TPL'] ?? '{title}';
$comment_tpl = $advancenews['FB_COMMENT_TPL'] ?? "বিস্তারিত: {title}\n\nলিংক: {link}";
$caption = fb_pc_clean_text(str_replace(array_keys($shortcodes), array_values($shortcodes), $caption_tpl));
$comment = fb_pc_clean_text(str_replace(array_keys($shortcodes), array_values($shortcodes), $comment_tpl));

// ---- 3) POST /{page-id}/photos ----
// Use multipart source upload first. This avoids Facebook re-fetch issues from hotlink/cPanel protections.
$photo_url = "https://graph.facebook.com/{$ver}/{$page_id}/photos";
$fields = [
    'caption'      => $caption,
    'access_token' => $token,
    'published'    => 'true',
];
if (class_exists('CURLFile')) {
    $fields['source'] = new CURLFile($filepath, $ext === 'png' ? 'image/png' : 'image/jpeg', $filename);
    [$http, $res, $cerr, $data] = fb_pc_graph_post($photo_url, $fields, 60);
} else {
    $fields['url'] = $public_url;
    [$http, $res, $cerr, $data] = fb_pc_graph_post($photo_url, http_build_query($fields), 60);
}

if ($http !== 200) {
    $err  = $data['error']['message'] ?? ($cerr ?: 'Unknown error');
    if (stripos($err, 'publish_actions') !== false) {
        $err = 'আপনার token পুরনো/deprecated publish_actions permission দিয়ে তৈরি। Meta এখন publish_actions নেয় না। Graph API Explorer থেকে pages_manage_posts + pages_read_engagement সহ নতুন Page Access Token বানিয়ে এখানে বসান। Original: '.$err;
    }
    out(false, 'Facebook-এ পোস্ট করা যায়নি: ' . $err);
}
$fb_post_id  = $data['post_id'] ?? ($data['id'] ?? '');
$fb_photo_id = $data['id'] ?? '';
if (!$fb_post_id) out(false, 'Facebook থেকে post_id পাওয়া যায়নি।');

// ---- 4) POST /{post_id}/comments (auto first comment as the Page) ----
// MUST be POST method, MUST use Page Access Token, MUST use the returned post_id
// from the /photos response. Requires pages_manage_engagement on the token.
$comment_ok  = true;
$comment_err = '';
if (trim($comment) !== '') {

    $do_comment = function($object_id) use ($ver, $comment, $token) {
        $cmt_url = "https://graph.facebook.com/{$ver}/" . rawurlencode($object_id) . "/comments";
        return fb_pc_graph_post($cmt_url, http_build_query([
            'message'      => $comment,
            'access_token' => $token,
        ]), 30);
    };

    // 1st try: comment on the story post_id (page_id_story_id) returned by /photos
    [$chttp, $cres, $cerr, $cdata] = $do_comment($fb_post_id);

    // Fallback: some setups only accept comments on the photo object id
    if ($chttp !== 200 && !empty($fb_photo_id) && $fb_photo_id !== $fb_post_id) {
        [$chttp, $cres, $cerr, $cdata] = $do_comment($fb_photo_id);
    }

    if ($chttp !== 200) {
        $comment_ok = false;
        $raw_err    = $cdata['error']['message'] ?? ($cerr ?: 'comment failed');
        $err_code   = $cdata['error']['code'] ?? '';
        if ($err_code == 200 || stripos($raw_err, 'permission') !== false) {
            $comment_err = 'Page Access Token-এ `pages_manage_engagement` permission নেই, তাই auto first-comment হচ্ছে না। Graph API Explorer-এ Page Token regenerate করে pages_manage_posts + pages_read_engagement + pages_manage_engagement তিনটি scope select করুন। (Original: '.$raw_err.')';
        } else {
            $comment_err = $raw_err;
        }
    }
}
// Build FB post URL
$pretty_id = str_replace($page_id . '_', '', $fb_post_id);
$fb_post_url = "https://www.facebook.com/{$page_id}/posts/{$pretty_id}";

out(true,
    $comment_ok ? 'ফেসবুক পেজে সফলভাবে পোস্ট ও কমেন্ট হয়েছে!' : 'পোস্ট হয়েছে কিন্তু কমেন্ট ব্যর্থ: '.$comment_err,
    ['fb_post_id'=>$fb_post_id, 'fb_post_url'=>$fb_post_url, 'image_url'=>$public_url]
);
