<?php
require_once __DIR__.'/helpers.php';

/** Simple JSON POST */
function http_post_json(string $url, array $payload, array $headers=[]): array {
  $ch=curl_init($url);
  $headers=array_merge(['Content-Type: application/json'], $headers);
  curl_setopt_array($ch,[
    CURLOPT_RETURNTRANSFER=>true,
    CURLOPT_POST=>true,
    CURLOPT_HTTPHEADER=>$headers,
    CURLOPT_POSTFIELDS=>json_encode($payload),
    CURLOPT_TIMEOUT=>20,
  ]);
  $resp=curl_exec($ch);
  if($resp===false){ $err=curl_error($ch); curl_close($ch); return ['ok'=>false,'error'=>$err,'status'=>0,'body'=>null]; }
  $code=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE);
  curl_close($ch);
  $body=json_decode($resp,true);
  return ['ok'=>$code>=200 && $code<300,'status'=>$code,'body'=>$body,'raw'=>$resp];
}

/** Form POST (application/x-www-form-urlencoded) */
function http_post_form(string $url, array $payload): array {
  $ch=curl_init($url);
  curl_setopt_array($ch,[
    CURLOPT_RETURNTRANSFER=>true,
    CURLOPT_POST=>true,
    CURLOPT_POSTFIELDS=>http_build_query($payload),
    CURLOPT_TIMEOUT=>20,
  ]);
  $resp=curl_exec($ch);
  if($resp===false){ $err=curl_error($ch); curl_close($ch); return ['ok'=>false,'error'=>$err,'status'=>0,'body'=>null]; }
  $code=(int)curl_getinfo($ch,CURLINFO_HTTP_CODE);
  curl_close($ch);
  $json=json_decode($resp,true);
  return ['ok'=>$code>=200 && $code<300,'status'=>$code,'body'=>$json,'raw'=>$resp];
}

/** WhatsApp sender (Wabot.my provider) */
function send_whatsapp(string $phone, string $message): bool {
  // Ambil tetapan khusus untuk Wabot dari database
  $instance_id = setting('WABOT_INSTANCE_ID','');
  $access_token = setting('WABOT_ACCESS_TOKEN','');

  // Jika salah satu maklumat tiada, batalkan penghantaran
  if(!$instance_id || !$access_token) {
    // Tulis ke log jika tetapan tidak lengkap
    file_put_contents(__DIR__.'/whatsapp_log.txt', date('Y-m-d H:i:s') . " - Gagal: Wabot Instance ID atau Access Token tidak ditetapkan.\n", FILE_APPEND);
    return false;
  }

  // URL tetap untuk API hantar mesej Wabot
  $url = 'https://app.wabot.my/api/send';
  
  // Sediakan data (payload) dalam format JSON seperti yang dikehendaki oleh Wabot
  $payload = [
    'number'       => $phone,
    'type'         => 'text',
    'message'      => $message,
    'instance_id'  => $instance_id,
    'access_token' => $access_token
  ];
  
  // Hantar permintaan POST dengan data JSON
  $res = http_post_json($url, $payload, []);
  
  // Baris untuk rekod log - simpan respons dari Wabot
  file_put_contents(__DIR__.'/whatsapp_log.txt', date('Y-m-d H:i:s') . " - Hantar ke: {$phone} - Respons: " . print_r($res, true) . "\n", FILE_APPEND);

  // Kembalikan 'true' jika penghantaran berjaya (status 2xx)
  return (bool)$res['ok'];
}

/** ToyyibPay: create bill, return payment URL + billCode */
function toyyibpay_create_bill(array $order): array {
  $apiKey = setting('TOYYIBPAY_API_KEY','');
  $category = setting('TOYYIBPAY_CATEGORY_CODE','');
  $returnUrl = setting('TOYYIBPAY_RETURN_URL','');
  
  
$callbackSecret = setting('TOYYIBPAY_CALLBACK_SECRET','');
if(!$apiKey || !$category) return ['ok'=>False,'error'=>'ToyyibPay not configured'];
$amountSen = (int)round(((float)$order['amount'])*100);
$billName = 'Order #'.$order['id'].' - '.$order['package_name'];
$desc = 'MukminRich | '.$order['name'].' | '.$order['phone'];

// --- KOD PEMBETULAN MULA ---
// Bina Base URL daripada Return URL untuk memastikan ia betul
$parsedUrl = parse_url($returnUrl);
$baseUrl = ($parsedUrl['scheme'] ?? 'https') . '://' . ($parsedUrl['host'] ?? '');
$callbackUrl = $baseUrl . '/toyyibpay_webhook.php';
// --- KOD PEMBETULAN TAMAT ---
  
  
  $res = http_post_form('https://toyyibpay.com/index.php/api/createBill',[
    'userSecretKey'=>$apiKey,
    'categoryCode'=>$category,
    'billName'=>$billName,
    'billDescription'=>$desc,
    'billPriceSetting'=>1,
    'billPayorInfo'=>1,
    'billAmount'=>$amountSen,
    'billReturnUrl'=>$returnUrl,
    'billCallbackUrl'=>$callbackUrl,
    'billExternalReferenceNo' => $order['id'], // <--- TAMBAH BARIS INI
    'billTo'=>$order['name'],
    'billEmail'=>$order['email'] ?? '',
    'billPhone'=>$order['phone'],
  ]);
  
  // Baris di bawah ini adalah versi yang telah dibaiki untuk mengelakkan ralat
  if(!$res['ok']) return ['ok'=>false, 'error'=>($res['error'] ?? 'HTTP Error '.$res['status'])];

  $body = $res['body'];
  if(is_array($body) && isset($body[0]['BillCode'])){
    $billCode = $body[0]['BillCode'];
    $url = 'https://toyyibpay.com/'.$billCode;
    return ['ok'=>true,'bill_code'=>$billCode,'url'=>$url];
  }
  return ['ok'=>false,'error'=>'Unexpected response: '.($res['raw'] ?? 'Empty response')];
}

/** ToyyibPay: deactivate an existing bill */
function toyyibpay_inactive_bill(string $billCode): array {
  $apiKey = setting('TOYYIBPAY_API_KEY','');
  if(!$apiKey) return ['ok' => false, 'error' => 'ToyyibPay API Key not configured'];

  // Nota: Endpoint ini menggunakan 'secretKey' bukannya 'userSecretKey'
  $res = http_post_form('https://toyyibpay.com/index.php/api/inactiveBill', [
    'secretKey' => $apiKey,
    'billCode' => $billCode
  ]);

  if(!$res['ok']) return ['ok' => false, 'error' => ($res['error'] ?? 'HTTP Error '.$res['status'])];

  // Semak jika respons mengandungi status 'success'
  if(isset($res['body']['status']) && $res['body']['status'] === 'success') {
    return ['ok' => true];
  }

  return ['ok' => false, 'error' => 'Failed to deactivate bill', 'response' => $res['body']];
}