<?php
require_once('config.php');

function fb_pc_clean_text($value) {
    $value = is_string($value) ? trim($value) : '';
    // The current tt_info table uses MySQL utf8, so 4-byte emoji can trigger HTTP 500.
    return preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $value);
}

function fb_pc_save_setting($key, $value) {
    global $conn;
    $exists = getAdvanceNews($key) !== 'not_available_create_new';
    if ($exists) {
        $stmt = $conn->prepare('UPDATE tt_info SET InfoValue = :value WHERE InfoName = :name');
    } else {
        $stmt = $conn->prepare('INSERT INTO tt_info (InfoName, InfoValue) VALUES (:name, :value)');
    }
    return $stmt->execute([':name' => $key, ':value' => $value]);
}

function fb_pc_graph_get($url) {
    $ch  = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $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)];
}

// Save Settings
if (isset($_POST['save_fb_settings'])) {
    $fields = [
        'FB_AUTO_SHARE_ENABLED' => isset($_POST['fb_enabled']) ? 'on' : 'off',
        'FB_APP_ID'             => fb_pc_clean_text($_POST['fb_app_id'] ?? ''),
        'FB_APP_SECRET'         => fb_pc_clean_text($_POST['fb_app_secret'] ?? ''),
        'FB_PAGE_ID'            => fb_pc_clean_text($_POST['fb_page_id'] ?? ''),
        'FB_PAGE_TOKEN'         => fb_pc_clean_text($_POST['fb_page_token'] ?? ''),
        'FB_GRAPH_VERSION'      => fb_pc_clean_text($_POST['fb_graph_version'] ?? 'v23.0'),
        'FB_CAPTION_TPL'        => fb_pc_clean_text($_POST['fb_caption_tpl'] ?? '{title}'),
        'FB_COMMENT_TPL'        => fb_pc_clean_text($_POST['fb_comment_tpl'] ?? "বিস্তারিত: {title}\n\nলিংক: {link}"),
    ];
    try {
        foreach ($fields as $k => $v) { fb_pc_save_setting($k, $v); }
        $tt_alert = ttAlert('success', 'Facebook Auto-Share সেটিংস সংরক্ষিত হয়েছে।');
        foreach ($fields as $k => $v) { $advancenews[$k] = $v; }
    } catch (Throwable $e) {
        $tt_alert = ttAlert('danger', 'সেটিংস সেভ করা যায়নি: '.$e->getMessage());
    }
}

// Test connection
$test_result = null;
if (isset($_POST['test_fb_connection'])) {
    $page_id = $advancenews['FB_PAGE_ID'] ?? '';
    $token   = $advancenews['FB_PAGE_TOKEN'] ?? '';
    $ver     = $advancenews['FB_GRAPH_VERSION'] ?? 'v23.0';
    if ($page_id && $token) {
        $url = "https://graph.facebook.com/{$ver}/{$page_id}?fields=id,name&access_token=" . urlencode($token);
        [$http, $res, $curl_err, $data] = fb_pc_graph_get($url);
        if ($http === 200 && !empty($data['name'])) {
            $perm_note = '';
            $app_id = $advancenews['FB_APP_ID'] ?? '';
            $app_secret = $advancenews['FB_APP_SECRET'] ?? '';
            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);
                $scopes = $debug['data']['scopes'] ?? [];
                $needed = ['pages_manage_posts', 'pages_read_engagement'];
                $missing = array_values(array_diff($needed, $scopes));
                if (!empty($missing)) {
                    $perm_note = '<br><span class="text-danger">সতর্কতা: Token-এ '.htmlentities(implode(', ', $missing)).' permission দেখা যাচ্ছে না। Share fail করতে পারে।</span>';
                } else {
                    $perm_note = '<br><span class="text-success">Token permission OK: pages_manage_posts + pages_read_engagement</span>';
                }
            } else {
                $perm_note = '<br><span class="text-warning">App ID/Secret দিলে Test Connection permission-ও যাচাই করবে।</span>';
            }
            $test_result = ['ok'=>true, 'msg'=>'কানেকশন সফল! পেজ: <strong>'.htmlentities($data['name']).'</strong> (ID: '.$data['id'].')'.$perm_note];
        } else {
            $err = $data['error']['message'] ?? ($curl_err ?: 'Unknown error');
            $test_result = ['ok'=>false, 'msg'=>'কানেকশন ব্যর্থ: '.htmlentities($err)];
        }
    } else {
        $test_result = ['ok'=>false, 'msg'=>'প্রথমে Page ID ও Page Access Token সংরক্ষণ করুন।'];
    }
}

require_once('inc/header.php');

$v = function($k, $d='') use ($advancenews) {
    return htmlentities($advancenews[$k] ?? $d, ENT_QUOTES, 'utf-8');
};
?>
<style>
.fb-card{background:#fff;border-radius:12px;box-shadow:0 2px 10px rgba(0,0,0,.06);margin-bottom:20px;overflow:hidden}
.fb-card-head{background:linear-gradient(135deg,#1877F2 0%,#0a4d9c 100%);color:#fff;padding:16px 20px}
.fb-card-head h5{margin:0;font-size:17px;font-weight:600}
.fb-card-body{padding:24px}
.fb-help{font-size:12.5px;color:#64748b;margin-top:5px;line-height:1.6}
.fb-help code{background:#eef2f7;padding:1px 6px;border-radius:4px;color:#0a4d9c}
.fb-status{padding:10px 14px;border-radius:8px;font-size:14px}
.fb-status.ok{background:#dcfce7;color:#166534;border:1px solid #86efac}
.fb-status.bad{background:#fee2e2;color:#991b1b;border:1px solid #fca5a5}
.fb-step{border-left:3px solid #1877F2;padding:10px 14px;background:#f8fafc;margin-bottom:10px;border-radius:0 8px 8px 0}
.fb-step b{color:#0a4d9c}
</style>

<main id="main" class="main">
  <div class="pagetitle d-flex align-items-center justify-content-between">
    <h1><i class="bi bi-facebook me-2" style="color:#1877F2"></i> Facebook Auto Sharing — Photo Card</h1>
    <a href="photocard.php" class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-left"></i> Back to Photocards</a>
  </div>

  <?php echo $tt_alert ?? ''; ?>
  <?php if ($test_result): ?>
    <div class="fb-status <?php echo $test_result['ok']?'ok':'bad'; ?> mb-3">
      <i class="bi bi-<?php echo $test_result['ok']?'check-circle-fill':'x-circle-fill'; ?>"></i>
      <?php echo $test_result['msg']; ?>
    </div>
  <?php endif; ?>

  <section class="section mt-3">
    <div class="row">
      <div class="col-lg-8">
        <form method="post" autocomplete="off">
          <div class="fb-card">
            <div class="fb-card-head"><h5><i class="bi bi-gear-fill"></i> Connection Settings</h5></div>
            <div class="fb-card-body">

              <div class="form-check form-switch mb-4" style="font-size:16px">
                <input class="form-check-input" type="checkbox" id="fb_enabled" name="fb_enabled" <?php echo (($advancenews['FB_AUTO_SHARE_ENABLED'] ?? 'off')==='on')?'checked':''; ?> style="width:48px;height:24px">
                <label class="form-check-label ms-2" for="fb_enabled"><strong>Auto Share চালু করুন</strong></label>
                <div class="fb-help">বন্ধ থাকলে single-post পেজে Share বাটন দেখা যাবে না।</div>
              </div>

              <div class="row g-3">
                <div class="col-md-6">
                  <label class="form-label">Facebook App ID</label>
                  <input type="text" name="fb_app_id" class="form-control" value="<?php echo $v('FB_APP_ID'); ?>" placeholder="1234567890123456">
                  <div class="fb-help">Meta for Developers → আপনার App → Settings → Basic</div>
                </div>
                <div class="col-md-6">
                  <label class="form-label">Facebook App Secret</label>
                  <input type="password" name="fb_app_secret" class="form-control" value="<?php echo $v('FB_APP_SECRET'); ?>" placeholder="••••••••••••">
                  <div class="fb-help">একই জায়গায় Show করে কপি করুন।</div>
                </div>
                <div class="col-md-6">
                  <label class="form-label">Facebook Page ID</label>
                  <input type="text" name="fb_page_id" class="form-control" value="<?php echo $v('FB_PAGE_ID'); ?>" placeholder="100000000000000" required>
                  <div class="fb-help">আপনার Page → About → Page ID</div>
                </div>
                <div class="col-md-6">
                  <label class="form-label">Graph API Version</label>
                  <input type="text" name="fb_graph_version" class="form-control" value="<?php echo $v('FB_GRAPH_VERSION','v23.0'); ?>">
                  <div class="fb-help">২০২৬ সালে stable version যেমন <code>v23.0</code> ব্যবহার করুন; Meta নতুন version দিলে এখানে বদলাতে পারবেন</div>
                </div>
                <div class="col-12">
                  <label class="form-label">Page Access Token <span class="text-danger">(Long-Lived)</span></label>
                  <textarea name="fb_page_token" class="form-control" rows="3" placeholder="EAAJ..."><?php echo $v('FB_PAGE_TOKEN'); ?></textarea>
                  <div class="fb-help">Graph API Explorer-এ <b>User/Page</b> নয়, অবশ্যই <b>Page Access Token</b> বসাবেন। Token Debugger-এ scopes-এ <code>pages_manage_posts</code>, <code>pages_read_engagement</code>, <code>pages_show_list</code> থাকতে হবে।</div>
                </div>
              </div>
            </div>
          </div>

          <div class="fb-card">
            <div class="fb-card-head" style="background:linear-gradient(135deg,#16a34a 0%,#15803d 100%)"><h5><i class="bi bi-card-text"></i> Post Format Templates</h5></div>
            <div class="fb-card-body">
              <div class="mb-3">
                <label class="form-label">Photo Caption (পোস্টের ছবির সাথে যাবে)</label>
                <textarea name="fb_caption_tpl" class="form-control" rows="2"><?php echo $v('FB_CAPTION_TPL','{title}'); ?></textarea>
                <div class="fb-help">শর্টকোড: <code>{title}</code>, <code>{category}</code>, <code>{date}</code>, <code>{link}</code></div>
              </div>
              <div class="mb-2">
                <label class="form-label">First Comment Template (অটো কমেন্টে যাবে)</label>
                <textarea name="fb_comment_tpl" class="form-control" rows="4"><?php echo $v('FB_COMMENT_TPL',"বিস্তারিত: {title}\n\nলিংক: {link}"); ?></textarea>
                <div class="fb-help">একই শর্টকোড সাপোর্টেড। নিউজ লিংক <code>{link}</code> বসান।</div>
              </div>
            </div>
          </div>

          <div class="d-flex gap-2">
            <button type="submit" name="save_fb_settings" class="btn btn-primary px-4"><i class="bi bi-save"></i> Save Settings</button>
            <button type="submit" name="test_fb_connection" class="btn btn-outline-success"><i class="bi bi-plug"></i> Test Connection</button>
          </div>
        </form>
      </div>

      <div class="col-lg-4">
        <div class="fb-card">
          <div class="fb-card-head" style="background:linear-gradient(135deg,#f59e0b 0%,#d97706 100%)"><h5><i class="bi bi-lightbulb-fill"></i> দ্রুত গাইডলাইন</h5></div>
          <div class="fb-card-body" style="font-size:14px">
            <div class="fb-step"><b>স্টেপ ১:</b> <a href="https://developers.facebook.com/apps/" target="_blank">developers.facebook.com/apps</a> → Create App → Type: <b>Business</b></div>
            <div class="fb-step"><b>স্টেপ ২:</b> App-এ <b>Facebook Login</b> + <b>Pages API</b> product যোগ করুন</div>
            <div class="fb-step"><b>স্টেপ ৩:</b> Permissions লাগবে: <code>pages_manage_posts</code>, <code>pages_read_engagement</code>, <code>pages_show_list</code></div>
            <div class="fb-step"><b>স্টেপ ৪:</b> Graph API Explorer → permissions টিক দিন → Generate User Token → তারপর <code>/me/accounts</code> চালিয়ে নিজের Page-এর <b>access_token</b> কপি করুন</div>
            <div class="fb-step"><b>স্টেপ ৫:</b> Access Token Debugger-এ token দেখে নিশ্চিত করুন scopes-এ <code>publish_actions</code> নেই এবং <code>pages_manage_posts</code> আছে</div>
            <div class="fb-step"><b>স্টেপ ৬:</b> Live mode-এ যেতে App Review দিন (test mode-এ শুধু App admin/role-এর পেজে পোস্ট হবে)</div>
            <div class="fb-step text-success"><b>✓ Test Connection</b> বাটনে সবুজ status এলে Setup সফল</div>
          </div>
        </div>
      </div>
    </div>
  </section>
</main>
<?php require_once('inc/footer.php'); ?>
