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

// Telegram settings (SECOND channel for installed guarantees)
$BOT_TOKEN = '490048283:AAGEC4Cj0c8SkIicNrMXl7QNDLC2rKK5LAs';
$CHAT_ID   = '-1003058637754';

function esc($s){ return htmlspecialchars(trim($s ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

// One-time code guard
$usedFile = __DIR__ . '/used_codes.json';
if(!file_exists($usedFile)) file_put_contents($usedFile, json_encode([]));
$used = json_decode(file_get_contents($usedFile), true);
if(!is_array($used)) $used = [];

$code = esc($_POST['code'] ?? '');
if($code === ''){ echo json_encode(['success'=>false,'error'=>'کد رهگیری نامعتبر است.']); exit; }
if(in_array($code, $used)){ echo json_encode(['success'=>false,'error'=>'این لینک قبلاً استفاده شده است.']); exit; }

// Carry-over (readonly) fields
$seller   = esc($_POST['seller'] ?? '');
$customer = esc($_POST['customer'] ?? '');
$province = esc($_POST['province'] ?? '');
$address  = esc($_POST['address'] ?? '');
$mobile   = esc($_POST['mobile'] ?? '');
$model    = esc($_POST['model'] ?? '');
$warranty = esc($_POST['warranty'] ?? '');

// Installer fields
$installer_name = esc($_POST['installer_name'] ?? '');
$install_date   = esc($_POST['install_date'] ?? '');
$serial_number  = esc($_POST['serial_number'] ?? '');
$notes          = esc($_POST['notes'] ?? '');

if($installer_name==='' || $install_date==='' || $serial_number===''){
  echo json_encode(['success'=>false,'error'=>'فیلدهای سرویس‌کار ناقص است.']); exit;
}

// Signatures (base64 images in hidden inputs)
$sign_c = $_POST['signature_customer'] ?? '';
$sign_i = $_POST['signature_installer'] ?? '';
function save_base64_image($data, $prefix){
  if(strpos($data, 'data:image') !== 0) return null;
  $parts = explode(',', $data, 2);
  if(count($parts) != 2) return null;
  $meta = $parts[0]; $bin = base64_decode($parts[1]);
  $ext = 'png'; if(strpos($meta,'image/jpeg')!==false) $ext='jpg';
  $dir = __DIR__ . '/uploads';
  if(!is_dir($dir)) mkdir($dir, 0775, true);
  $name = $dir . '/' . $prefix . '_' . uniqid() . '.' . $ext;
  file_put_contents($name, $bin);
  return $name;
}
$sign_path_c = save_base64_image($sign_c, 'sigc');
$sign_path_i = save_base64_image($sign_i, 'sigi');

// Photo upload
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;
}
$photo_path = save_upload('photo');
if(!$photo_path){ echo json_encode(['success'=>false,'error'=>'عکس نصب اجباری است.']); exit; }

// Build HTML message
$lines = [];
$lines[] = "<b>نصب انجام شد ✅</b>";
$lines[] = "<b>کد رهگیری:</b> ". $code;
$lines[] = "<b>مشخصات مشتری</b>";
$lines[] = "• <b>نام:</b> ". $customer;
$lines[] = "• <b>استان:</b> ". $province;
$lines[] = "• <b>آدرس:</b> ". $address;
$lines[] = "• <b>همراه:</b> ". $mobile;
$lines[] = "<b>مشخصات کالا</b>";
$lines[] = "• <b>مدل:</b> ". $model;
if($warranty!=='') $lines[] = "• <b>گارانتی:</b> ". $warranty;
$lines[] = "<b>اطلاعات نصب</b>";
$lines[] = "• <b>سرویس‌کار:</b> ". $installer_name;
$lines[] = "• <b>تاریخ نصب:</b> ". $install_date;
$lines[] = "• <b>سریال:</b> ". $serial_number;
if($notes!=='') $lines[] = "• <b>توضیحات:</b> ". $notes;
$lines[] = "<i>ارسال خودکار از salambaba.co/guaranti - ".date('Y-m-d H:i')."</i>";
$caption = implode("\n", $lines);

// Send photo first (with caption)
$payloadPhoto = [
  'chat_id' => $CHAT_ID,
  'caption' => $caption,
  'parse_mode' => 'HTML'
];
$ch = curl_init("https://api.telegram.org/bot{$BOT_TOKEN}/sendPhoto");
curl_setopt_array($ch,[
  CURLOPT_POST=>true,
  CURLOPT_RETURNTRANSFER=>true,
  CURLOPT_POSTFIELDS=> $payloadPhoto + ['photo' => new CURLFile($photo_path)],
  CURLOPT_TIMEOUT=>20,
  CURLOPT_SSL_VERIFYPEER=>false,
  CURLOPT_SSL_VERIFYHOST=>false
]);
$res1 = curl_exec($ch);
curl_close($ch);

// Then send signatures (if available)
if($sign_path_c || $sign_path_i){
  $pieces = [];
  if($sign_path_c) $pieces[] = ['path'=>$sign_path_c, 'label'=>'امضای مشتری'];
  if($sign_path_i) $pieces[] = ['path'=>$sign_path_i, 'label'=>'امضای سرویس‌کار'];
  foreach($pieces as $p){
    $payloadSig = [
      'chat_id' => $CHAT_ID,
      'caption' => $p['label'],
      'parse_mode' => 'HTML'
    ];
    $ch = curl_init("https://api.telegram.org/bot{$BOT_TOKEN}/sendPhoto");
    curl_setopt_array($ch,[
      CURLOPT_POST=>true,
      CURLOPT_RETURNTRANSFER=>true,
      CURLOPT_POSTFIELDS=> $payloadSig + ['photo' => new CURLFile($p['path'])],
      CURLOPT_TIMEOUT=>20,
      CURLOPT_SSL_VERIFYPEER=>false,
      CURLOPT_SSL_VERIFYHOST=>false
    ]);
    curl_exec($ch);
    curl_close($ch);
  }
}

// Mark code as used
$used[] = $code;
file_put_contents($usedFile, json_encode($used, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));

echo json_encode(['success'=>true,'code'=>$code]);
exit;
