<?php
header('Content-Type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__.'/config.php';
$mysqli = db();

function clean($s){ return trim($s ?? ''); }

$seller = clean($_POST['seller'] ?? '');
$customer_name = clean($_POST['customer_name'] ?? '');
$province = clean($_POST['province'] ?? '');
$address  = clean($_POST['address'] ?? '');
$mobile   = clean($_POST['mobile'] ?? '');
$phone    = clean($_POST['phone'] ?? '');
$model    = clean($_POST['model'] ?? '');
$warranty = clean($_POST['warranty'] ?? '');
$purchase_jalali = clean($_POST['purchase_jalali'] ?? '');
$notes    = clean($_POST['notes'] ?? '');

$missing=[];
if($customer_name==='') $missing[]='نام مشتری';
if($province==='')      $missing[]='استان';
if($address==='')       $missing[]='آدرس';
if($mobile==='')        $missing[]='همراه';
if($model==='')         $missing[]='مدل';
if($seller==='')        $missing[]='فروشنده';
if($missing){ echo json_encode(['success'=>false,'error'=>'فیلدهای لازم: '.implode('، ',$missing)], JSON_UNESCAPED_UNICODE); exit; }

$tracking = gen_tracking();

$stmt = $mysqli->prepare("INSERT INTO guarantee_requests (tracking_code, seller, customer_name, province, address, mobile, phone, model, warranty, purchase_date, notes) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("sssssssssss", $tracking,$seller,$customer_name,$province,$address,$mobile,$phone,$model,$warranty,$purchase_jalali,$notes);
if(!$stmt->execute()){ echo json_encode(['success'=>false,'error'=>'DB insert failed: '.$stmt->error], JSON_UNESCAPED_UNICODE); exit; }
$stmt->close();

$install_link = "https://salambaba.co/guaranti/install.php?"
  ."code=".urlencode($tracking)
  ."&seller=".urlencode($seller)
  ."&customer=".urlencode($customer_name)
  ."&province=".urlencode($province)
  ."&address=".urlencode($address)
  ."&mobile=".urlencode($mobile)
  ."&model=".urlencode($model)
  ."&warranty=".urlencode($warranty);

$lines=[];
$lines[]="<b>فرم جدید درخواست نصب</b>";
$lines[]="<b>کد رهگیری:</b> ".esc_html($tracking);
$lines[]="<b>فروشنده:</b> ".esc_html($seller);
$lines[]="<b>مشتری:</b> ".esc_html($customer_name);
$lines[]="<b>استان:</b> ".esc_html($province);
$lines[]="<b>آدرس:</b> ".esc_html($address);
$lines[]="<b>همراه:</b> ".esc_html($mobile).($phone?" | <b>ثابت:</b> ".esc_html($phone):"");
$lines[]="<b>مدل:</b> ".esc_html($model);
if($warranty!=='') $lines[]="<b>گارانتی:</b> ".esc_html($warranty);
if($purchase_jalali!=='') $lines[]="<b>تاریخ خرید:</b> ".esc_html($purchase_jalali);
if($notes!=='') $lines[]="<b>توضیحات فروشنده:</b> ".esc_html($notes);
$lines[]="<b>📎 لینک فرم نصب:</b> <a href=\"".esc_html($install_link)."\">فرم تکمیل نصب</a>";
$lines[]="<i>ارسال از salambaba.co/guaranti — ".date('Y-m-d H:i')."</i>";
tg_send_message(TG_CHAT_REQUESTS, implode("\n",$lines));

echo json_encode(['success'=>true,'tracking'=>$tracking,'install_link'=>$install_link], JSON_UNESCAPED_UNICODE);
?>