<?php
require_once '../includes/auth.php';
require_once 'functions.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

pic_ensure_schema($conn);
pic_refresh_used_flags($conn);

$q = trim((string)($_GET['q'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 50;
$offset = ($page - 1) * $limit;
$where = '';
$params = [];
$types = '';
if ($q !== '') {
    $like = '%' . $q . '%';
    $where = 'WHERE internal_name LIKE ? OR internal_slug LIKE ? OR barcode LIKE ?';
    $params = [$like, $like, $like];
    $types = 'sss';
}
$countSql = "SELECT COUNT(*) c FROM product_import_catalog {$where}";
$stmt = $conn->prepare($countSql);
if ($params) { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$total = (int)(($stmt->get_result()->fetch_assoc()['c'] ?? 0));
$stmt->close();

$sql = "SELECT * FROM product_import_catalog {$where} ORDER BY is_used ASC, updated_at DESC, id DESC LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
if ($params) {
    $types2 = $types . 'ii';
    $params2 = array_merge($params, [$limit, $offset]);
    $stmt->bind_param($types2, ...$params2);
} else {
    $stmt->bind_param('ii', $limit, $offset);
}
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();
$pages = max(1, (int)ceil($total / $limit));
function h($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
?>
<style>
.pic-page{direction:rtl;padding:24px}.pic-wrap{max-width:1400px;margin:auto}.pic-head{display:flex;justify-content:space-between;gap:16px;align-items:flex-start;flex-wrap:wrap;margin-bottom:20px}.pic-head h1{margin:0 0 6px;color:#17324d;font-size:28px;font-weight:900}.pic-head p{margin:0;color:#6b7c93}.pic-actions{display:flex;gap:10px;flex-wrap:wrap}.pic-btn{border:0;border-radius:14px;padding:12px 16px;font-weight:800;text-decoration:none;cursor:pointer;display:inline-flex;gap:8px;align-items:center}.pic-btn.primary{background:linear-gradient(135deg,#2f80ed,#56ccf2);color:#fff}.pic-btn.light{background:#fff;color:#17324d;border:1px solid #d9e6f2}.pic-card{background:#fff;border:1px solid #edf2f7;border-radius:22px;box-shadow:0 12px 35px rgba(16,24,40,.06);overflow:hidden}.pic-toolbar{padding:16px;border-bottom:1px solid #edf2f7;display:flex;gap:10px;flex-wrap:wrap}.pic-toolbar input{min-width:280px;flex:1;border:1px solid #d8e4ef;border-radius:14px;padding:13px 14px}.pic-table{width:100%;border-collapse:collapse}.pic-table th,.pic-table td{padding:13px 14px;border-bottom:1px solid #f0f3f7;text-align:right;font-size:13px}.pic-table th{background:#f8fbfe;color:#47637f;font-weight:900}.pic-table td{color:#17324d}.badge{display:inline-flex;padding:6px 10px;border-radius:999px;font-weight:900;font-size:12px}.badge.used{background:#ffecec;color:#b42318}.badge.free{background:#eafff4;color:#027a48}.mono{direction:ltr;unicode-bidi:bidi-override;font-family:monospace}.notice{padding:14px 16px;border-radius:16px;margin-bottom:16px;font-weight:800}.notice.ok{background:#ecfdf3;color:#027a48;border:1px solid #abefc6}.notice.err{background:#fff1f1;color:#b42318;border:1px solid #fecaca}.pager{padding:16px;display:flex;gap:8px;justify-content:center;flex-wrap:wrap}.pager a{padding:8px 12px;border:1px solid #d9e6f2;border-radius:10px;text-decoration:none;color:#17324d}.pager a.active{background:#17324d;color:#fff}
</style>
<div class="pic-page"><div class="pic-wrap">
  <div class="pic-head">
    <div><h1>كتالوج المنتجات الداخلي</h1><p>ارفع ملف Excel/CSV للمواد الداخلية. بعدها تختار المادة من صفحة إضافة المنتج فيتعبى الباركود والسعر تلقائياً.</p></div>
    <div class="pic-actions"><a class="pic-btn primary" href="import.php">رفع ملف جديد</a><a class="pic-btn light" href="../products/create.php">إضافة منتج</a></div>
  </div>
  <?php if (!empty($_SESSION['pic_success'])): ?><div class="notice ok"><?= h($_SESSION['pic_success']); unset($_SESSION['pic_success']); ?></div><?php endif; ?>
  <?php if (!empty($_SESSION['pic_error'])): ?><div class="notice err"><?= h($_SESSION['pic_error']); unset($_SESSION['pic_error']); ?></div><?php endif; ?>
  <div class="pic-card">
    <form class="pic-toolbar" method="get"><input type="text" name="q" value="<?= h($q) ?>" placeholder="بحث بالاسم الداخلي / slug / barcode"><button class="pic-btn primary" type="submit">بحث</button><a class="pic-btn light" href="index.php">إعادة</a></form>
    <table class="pic-table"><thead><tr><th>#</th><th>الاسم الداخلي / Slug</th><th>Barcode</th><th>السعر</th><th>الحالة</th><th>منتج مرتبط</th></tr></thead><tbody>
    <?php if (!$rows): ?><tr><td colspan="6">لا توجد بيانات بعد.</td></tr><?php endif; ?>
    <?php foreach ($rows as $r): ?><tr>
      <td><?= (int)$r['id'] ?></td>
      <td><strong><?= h($r['internal_name']) ?></strong><br><small><?= h($r['internal_slug']) ?></small></td>
      <td class="mono"><?= h($r['barcode']) ?></td>
      <td><?= number_format((float)$r['price']) ?> د.ع</td>
      <td><?= ((int)$r['is_used'] === 1) ? '<span class="badge used">مستخدم</span>' : '<span class="badge free">متاح</span>' ?></td>
      <td><?= !empty($r['linked_product_id']) ? ('#' . (int)$r['linked_product_id']) : '-' ?></td>
    </tr><?php endforeach; ?>
    </tbody></table>
    <div class="pager"><?php for($i=1;$i<=$pages;$i++): ?><a class="<?= $i===$page?'active':'' ?>" href="?q=<?= urlencode($q) ?>&page=<?= $i ?>"><?= $i ?></a><?php endfor; ?></div>
  </div>
</div></div>
<?php require_once '../includes/footer.php'; ?>
