<?php
require __DIR__ . "/wa_config.php";
$PANEL_PIN = "1234";
header("Cache-Control: no-store");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  header("Content-Type: application/json; charset=utf-8");
  if (($_POST['pin'] ?? '') !== $PANEL_PIN) { http_response_code(403); echo json_encode(["error"=>"Forbidden: wrong PIN"]); exit; }

  $to            = preg_replace('/\D+/', '', $_POST['to'] ?? '');
  $template_name = trim($_POST['template_name'] ?? '');
  $lang_code     = trim($_POST['language_code'] ?? 'en_US');
  $params_raw    = trim($_POST['body_params'] ?? '');
  $header_type   = trim($_POST['header_type'] ?? '');
  $header_value  = trim($_POST['header_value'] ?? '');

  if (!$to || !$template_name) { http_response_code(400); echo json_encode(["error"=>"Missing fields: 'to' and 'template_name' required"]); exit; }
  if (empty($WA_PHONE_NUMBER_ID) || empty($WA_TOKEN) || empty($GRAPH_VERSION)) { http_response_code(500); echo json_encode(["error"=>"Server config missing in wa_config.php"]); exit; }

  $components = [];
  if ($header_type) {
    if ($header_type === 'text') {
      $components[] = ["type"=>"header","parameters"=>[["type"=>"text","text"=>$header_value]]];
    } elseif (in_array($header_type, ['image','video','document'], true)) {
      if (!$header_value) { http_response_code(400); echo json_encode(["error"=>"Header URL required for $header_type"]); exit; }
      $components[] = ["type"=>"header","parameters"=>[["type"=>$header_type, $header_type=>["link"=>$header_value]]]];
    }
  }
  $body_params = [];
  if ($params_raw !== '') {
    foreach (explode(',', $params_raw) as $p) { $p=trim($p); if ($p!=='') $body_params[] = ["type"=>"text","text"=>$p]; }
  }
  if ($body_params) $components[] = ["type"=>"body","parameters"=>$body_params];

  $payload = [
    "messaging_product"=>"whatsapp",
    "to"=>$to,
    "type"=>"template",
    "template"=>["name"=>$template_name, "language"=>["code"=>$lang_code]]
  ];
  if ($components) $payload["template"]["components"] = $components;

  $url = "https://graph.facebook.com/{$GRAPH_VERSION}/{$WA_PHONE_NUMBER_ID}/messages";
  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_HTTPHEADER => ["Authorization: Bearer {$WA_TOKEN}", "Content-Type: application/json"],
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_TIMEOUT => 30
  ]);
  $res  = curl_exec($ch);
  $err  = curl_error($ch);
  $http = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
  curl_close($ch);

  if ($err) { http_response_code(502); echo json_encode(["error"=>"cURL error","detail"=>$err]); exit; }
  http_response_code($http ?: 200);
  echo $res ?: json_encode(["ok"=>true,"note"=>"No response body"]);
  exit;
}
?>
<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Send WhatsApp Template</title>
<style>
  body{font:16px/1.5 system-ui,Arial;padding:16px;max-width:640px;margin:auto}
  label{font-weight:600;display:block;margin-top:10px}
  input,select,textarea,button{width:100%;padding:12px;margin-top:6px;border:1px solid #ddd;border-radius:8px}
  button{background:#111;color:#fff;margin-top:14px}
  small{color:#666}
  .row{display:grid;grid-template-columns:1fr 1fr;gap:8px}
  #resp{white-space:pre-wrap;background:#f7f7f7;border:1px solid #eee;border-radius:8px;padding:10px;margin-top:12px}
</style>

<h2>Send Template (WhatsApp)</h2>
<form id="f">
  <label>PIN</label>
  <input name="pin" placeholder="Enter PIN" required>

  <label>Recipient (E.164, no +)</label>
  <input name="to" placeholder="e.g. 919899654514" inputmode="numeric" required>

  <label>Template Name</label>
  <input name="template_name" placeholder="e.g. digital_services_offer" required>

  <div class="row">
    <div>
      <label>Language Code</label>
      <input name="language_code" value="en_US" required>
    </div>
    <div>
      <label>Body Params (comma-separated)</label>
      <input name="body_params" placeholder="Rahul, Today 5 PM">
      <small>Fills {{1}}, {{2}}, … if your template uses them</small>
    </div>
  </div>

  <div class="row">
    <div>
      <label>Header Type</label>
      <select name="header_type">
        <option value="">None</option>
        <option value="text">Text</option>
        <option value="image">Image (URL)</option>
        <option value="video">Video (URL)</option>
        <option value="document">Document (URL)</option>
      </select>
    </div>
    <div>
      <label>Header Value</label>
      <input name="header_value" placeholder="For text or media URL">
    </div>
  </div>

  <button type="submit">Send Template</button>
</form>

<pre id="resp"></pre>
<script>
document.getElementById('f').addEventListener('submit', async (e)=>{
  e.preventDefault();
  const fd = new FormData(e.target);
  const res = await fetch(location.href, { method:'POST', body: fd });
  const txt = await res.text();
  document.getElementById('resp').textContent = txt;
});
</script>