<?php
// /dalelapp/search.php
header('Content-Type: application/json; charset=utf-8');
mb_internal_encoding('UTF-8');

require_once __DIR__ . '/config/db.php';
$pdo->exec("SET NAMES utf8mb4");

$qRaw  = isset($_GET['q']) ? trim($_GET['q']) : '';
$DEBUG = isset($_GET['debug']) && $_GET['debug']=='1';
if ($qRaw === '') { echo json_encode([], JSON_UNESCAPED_UNICODE); exit; }

function tableExists(PDO $pdo, $table){
  $s=$pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=?");
  $s->execute([$table]); return (bool)$s->fetchColumn();
}
function hasColumn(PDO $pdo,$table,$col){
  $s=$pdo->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?");
  $s->execute([$table,$col]); return (bool)$s->fetchColumn();
}
function firstExisting(PDO $pdo,$table,$candidates){
  foreach($candidates as $c){ if(hasColumn($pdo,$table,$c)) return $c; }
  return null;
}
function statusClause(PDO $pdo,$table){
  foreach (['status','state','is_active','approved','published'] as $col){
    if (hasColumn($pdo,$table,$col)) return " AND ($col IN ('approved','active','published','موافق','1',1,'enabled','ok')) ";
  }
  return '';
}

/**
 * يبني شرط LIKE مع بارامترات فريدة لكل عمود: (:p1, :p2, ...)
 * ويرجع [clause, params]
 */
function buildLikeClause($alias, $cols, $value, $startIndex = 1){
  $parts = []; $params = []; $i = $startIndex;
  foreach ($cols as $c){
    if (!$c) continue;
    $isJoined = strpos($c, '.') !== false;    // مثل cat.name
    $qualified = $isJoined ? $c : "$alias.$c";
    $ph = ":p".$i++;
    $parts[] = "$qualified COLLATE utf8mb4_general_ci LIKE $ph";
    $params[$ph] = '%'.$value.'%';
  }
  if (!$parts) return ['1=0', [] , $i]; // لا شيء للبحث فيه
  return ['('.implode(' OR ', $parts).')', $params, $i];
}

$q = $qRaw;

try{
  $results = [];
  $debugCounts = ['companies'=>0,'offers'=>0,'posts'=>0];

  // ======== الشركات ========
  if (tableExists($pdo,'companies')){
    $cNameCol = hasColumn($pdo,'companies','name') ? 'name' : firstExisting($pdo,'companies',['company_name','title','label']);
    if (!$cNameCol) $cNameCol = 'id'; // احتياطي

    // أعمدة النص للبحث
    $cTextCols = array_values(array_filter([
      $cNameCol,
      firstExisting($pdo,'companies',['summary','description','about','details','notes','bio']),
      hasColumn($pdo,'companies','phone') ? 'phone' : null,
      hasColumn($pdo,'companies','whatsapp') ? 'whatsapp' : null,
    ]));

    $join = '';
    $joinedCols = [];
    if (tableExists($pdo,'categories') && hasColumn($pdo,'companies','category_id') && hasColumn($pdo,'categories','id') && hasColumn($pdo,'categories','name')){
      $join .= " LEFT JOIN categories cat ON c.category_id = cat.id ";
      $joinedCols[] = 'cat.name';
    }
    if (tableExists($pdo,'cities') && hasColumn($pdo,'companies','city_id') && hasColumn($pdo,'cities','id') && hasColumn($pdo,'cities','name')){
      $join .= " LEFT JOIN cities city ON c.city_id = city.id ";
      $joinedCols[] = 'city.name';
    }

    // ابني الشرط والبارامترات
    list($likeClause, $likeParams, $nextIdx) = buildLikeClause('c', array_merge($cTextCols, $joinedCols), $q, 1);
    $where = $likeClause . statusClause($pdo,'companies');

    // عمود المقتطف
    $snippetCol = firstExisting($pdo,'companies',['summary','description','about','details']);
    if (!$snippetCol) $snippetCol = $cNameCol;

    $sqlCompanies = "SELECT c.id, c.$cNameCol AS title, c.$snippetCol AS snippet
                     FROM companies c $join
                     WHERE $where
                     ORDER BY c.id DESC LIMIT 10";

    $st = $pdo->prepare($sqlCompanies);
    foreach ($likeParams as $k=>$v) $st->bindValue($k, $v, PDO::PARAM_STR);
    $st->execute();
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);
    $debugCounts['companies'] = count($rows);

    foreach ($rows as $r){
      $results[] = [
        'type'=>'company','type_ar'=>'شركة',
        'title'=>$r['title'],
        'snippet'=>mb_substr(strip_tags((string)$r['snippet']),0,120),
        'url'=>'/dalelapp/company.php?id='.(int)$r['id'],
      ];
    }
  }

  // ======== العروض ========
  if (tableExists($pdo,'offers')){
    $oTitle = firstExisting($pdo,'offers',['title','name']) ?: 'id';
    $oDesc  = firstExisting($pdo,'offers',['description','details','content','summary']) ?: $oTitle;

    list($likeClause, $likeParams) = buildLikeClause('o', [$oTitle,$oDesc], $q, 1);
    $where = $likeClause . statusClause($pdo,'offers');

    $sqlOffers = "SELECT o.id, o.$oTitle AS title, o.$oDesc AS description
                  FROM offers o
                  WHERE $where
                  ORDER BY o.id DESC LIMIT 10";
    $st = $pdo->prepare($sqlOffers);
    foreach ($likeParams as $k=>$v) $st->bindValue($k, $v, PDO::PARAM_STR);
    $st->execute();
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);
    $debugCounts['offers'] = count($rows);

    foreach ($rows as $r){
      $results[] = [
        'type'=>'offer','type_ar'=>'عرض',
        'title'=>$r['title'],
        'snippet'=>mb_substr(strip_tags((string)$r['description']),0,120),
        'url'=>'/dalelapp/offer.php?id='.(int)$r['id'],
      ];
    }
  }

  // ======== المدونة ========
  if (tableExists($pdo,'posts')){
    $pTitle = firstExisting($pdo,'posts',['title','name','heading']) ?: 'id';
    $pBody  = firstExisting($pdo,'posts',['content','body','text','description']) ?: $pTitle;

    list($likeClause, $likeParams) = buildLikeClause('p', [$pTitle,$pBody], $q, 1);
    $where = $likeClause . statusClause($pdo,'posts');

    $sqlPosts = "SELECT p.id, p.$pTitle AS title, p.$pBody AS content
                 FROM posts p
                 WHERE $where
                 ORDER BY p.id DESC LIMIT 10";
    $st = $pdo->prepare($sqlPosts);
    foreach ($likeParams as $k=>$v) $st->bindValue($k, $v, PDO::PARAM_STR);
    $st->execute();
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);
    $debugCounts['posts'] = count($rows);

    foreach ($rows as $r){
      $results[] = [
        'type'=>'post','type_ar'=>'مقال',
        'title'=>$r['title'],
        'snippet'=>mb_substr(strip_tags((string)$r['content']),0,120),
        'url'=>'/dalelapp/post.php?id='.(int)$r['id'],
      ];
    }
  }

  // لا نتائج؟ رجّع اقتراحات حديثة
  if (!count($results)){
    $fallback=[];
    if (tableExists($pdo,'companies')){
      $name = hasColumn($pdo,'companies','name') ? 'name' : 'id';
      $fb=$pdo->query("SELECT id, $name AS title FROM companies ORDER BY id DESC LIMIT 6")->fetchAll(PDO::FETCH_ASSOC);
      foreach($fb as $r){ $fallback[]=['type'=>'company','type_ar'=>'شركة','title'=>$r['title'],'snippet'=>'','url'=>'/dalelapp/company.php?id='.(int)$r['id']]; }
    }
    if (tableExists($pdo,'offers')){
      $t = hasColumn($pdo,'offers','title') ? 'title' : 'id';
      $fb=$pdo->query("SELECT id, $t AS title FROM offers ORDER BY id DESC LIMIT 6")->fetchAll(PDO::FETCH_ASSOC);
      foreach($fb as $r){ $fallback[]=['type'=>'offer','type_ar'=>'عرض','title'=>$r['title'],'snippet'=>'','url'=>'/dalelapp/offer.php?id='.(int)$r['id']]; }
    }
    if (tableExists($pdo,'posts')){
      $t = hasColumn($pdo,'posts','title') ? 'title' : 'id';
      $fb=$pdo->query("SELECT id, $t AS title FROM posts ORDER BY id DESC LIMIT 6")->fetchAll(PDO::FETCH_ASSOC);
      foreach($fb as $r){ $fallback[]=['type'=>'post','type_ar'=>'مقال','title'=>$r['title'],'snippet'=>'','url'=>'/dalelapp/post.php?id='.(int)$r['id']]; }
    }
    echo json_encode($fallback, JSON_UNESCAPED_UNICODE); exit;
  }

  if ($DEBUG) {
    echo json_encode(['debug'=>['q'=>$qRaw,'counts'=>$debugCounts],'results'=>$results], JSON_UNESCAPED_UNICODE);
    exit;
  }

  echo json_encode($results, JSON_UNESCAPED_UNICODE);

} catch(Throwable $e){
  if($DEBUG){
    echo json_encode([['type'=>'error','type_ar'=>'خطأ','title'=>'Server Error','snippet'=>$e->getMessage(),'url'=>'#']], JSON_UNESCAPED_UNICODE);
  } else {
    http_response_code(500);
    echo json_encode([]);
  }
}
