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

// Telegram (گروه درخواست نصب - فرم اول)
$BOT_TOKEN = '490048283:AAGEC4Cj0c8SkIicNrMXl7QNDLC2rKK5LAs';
$CHAT_ID   = '-1003122605108'; // گروه اول

// ---------------------- Helpers ----------------------
function esc_html($s){
    return htmlspecialchars(trim($s ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function gen_tracking($len=10){
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $t=''; for($i=0;$i<$len;$i++){ $t .= $chars[random_int(0, strlen($chars)-1)]; }
    return 'SBG'.date('y').$t;
}
function clean($s){ return htmlspecialchars(trim($s ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
function save_upload($field){
    if(!isset($_FILES[$field]) || $_FILES[$field]['error'] !== UPLOAD_ERR_OK) return null;
    $dir = __DIR__ . '/uploads';
    if(!is_dir($dir)) mkdir($dir, 0775, true);
    $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
    if(!in_array($ext, ['jpg','jpeg','png','webp','gif'])) $ext = 'jpg';
    $name = uniqid('u_',true).'.'.$ext;
    $dest = $dir.'/'.$name;
    if(move_uploaded_file($_FILES[$field]['tmp_name'], $dest)) return $dest;
    return null;
}

// ---------------------- Collect Data ----------------------
$seller = clean($_POST['seller'] ?? '');
if($seller === 'سایر'){ $seller = clean($_POST['seller_other'] ?? 'سایر'); }

$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'] ?? '');
$notes    = clean($_POST['notes'] ?? '');
$purchase_jalali = clean($_POST['purchase_jalali'] ?? '');
$purchase_greg   = clean($_POST['purchase_gregorian'] ?? '');

$items = $_POST['items'] ?? [];
if(!is_array($items)) $items = [];
$items = array_map('clean', $items);
if(in_array('سایر', $items)){
    $items = array_diff($items, ['سایر']);
    $item_other = clean($_POST['item_other'] ?? '');
    $items[] = 'سایر - ' . $item_other;
}

// ---------------------- Validation ----------------------
$missing = [];
if($customer_name==='') $missing[] = 'نام مشتری';
if($province==='')      $missing[] = 'استان';
if($address==='')       $missing[] = 'آدرس';
if($mobile==='')        $missing[] = 'شماره همراه';
if($model==='')         $missing[] = 'مدل کالا';

if(!empty($missing)){
  echo json_encode([
    'success' => false,
    'error'   => 'فیلدهای لازم پر نشده‌اند: ' . implode('، ', $missing)
  ]);
  exit;
}

// ---------------------- Uploads (اختیاری) ----------------------
$p1 = save_upload('photo1');
$p2 = save_upload('photo2');
$p3 = save_upload('photo3');

// ---------------------- Tracking ----------------------
$tracking = gen_tracking();

// ---------------------- Build Install Link (Form 2) ----------------------
$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);
$link_html = esc_html($install_link);

// ---------------------- Message (HTML-Safe) ----------------------
$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) : "");
if(!empty($items)) $lines[] = "<b>کالا:</b> ".esc_html(implode('، ', $items));
$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=\"{$link_html}\">فرم تکمیل نصب</a>";
$lines[] = "<i>ارسال از salambaba.co/guaranti — ".date('Y-m-d H:i')."</i>";
$caption = implode("\n", $lines);

// ---------------------- Telegram Send ----------------------
$media_paths = array_values(array_filter([$p1,$p2,$p3]));

if (empty($media_paths)) {
    // فقط پیام متنی
    $payload = [
        'chat_id' => $CHAT_ID,
        'text' => $caption,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];
    $ch = curl_init("https://api.telegram.org/bot{$BOT_TOKEN}/sendMessage");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
} else {
    // اگر عکس وجود دارد → اول عکس‌ها، بعد متن جداگانه
    $media = [];
    $files = [];
    $i = 0;
    foreach ($media_paths as $p) {
        $key = 'file'.$i;
        $media[] = ['type' => 'photo', 'media' => 'attach://'.$key];
        $files[$key] = new CURLFile($p);
        $i++;
    }
    $payload = [
        'chat_id' => $CHAT_ID,
        'media' => json_encode($media, JSON_UNESCAPED_UNICODE)
    ];
    $ch = curl_init("https://api.telegram.org/bot{$BOT_TOKEN}/sendMediaGroup");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => $payload + $files,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    $res = curl_exec($ch);
    curl_close($ch);

    // متن جداگانه (شامل لینک فرم نصب)
    $payload = [
        'chat_id' => $CHAT_ID,
        'text' => $caption,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => false
    ];
    $ch = curl_init("https://api.telegram.org/bot{$BOT_TOKEN}/sendMessage");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
}

// ---------------------- Final JSON ----------------------
echo json_encode(['success' => true, 'tracking' => $tracking, 'install_link' => $install_link]);
exit;
?>
