<?php
include "session.php";
ini_set('display_errors', 1);
error_reporting(E_ALL);

header("Cache-Control: no-cache, must-revalidate");

require_once __DIR__ . '/../db.php';

// ===== التحقق من وجود الأعمدة المطلوبة =====
try { $pdo->query("SELECT api_base_url FROM delivery_companies LIMIT 1"); }
catch (PDOException $e) { 
    $pdo->exec("ALTER TABLE delivery_companies ADD COLUMN api_base_url VARCHAR(255) NULL AFTER api_token");
}

// ========== إضافة شركة ==========
if (isset($_POST['add_company'])) {
    try {
        $name       = trim($_POST['company_name'] ?? '');
        $return_fee = floatval($_POST['return_fee'] ?? 200);
        $api_token  = trim($_POST['api_token'] ?? '');
        $api_base_url = trim($_POST['api_base_url'] ?? '');

        if (empty($name)) throw new Exception("اسم الشركة مطلوب");
        if (!empty($api_base_url) && !filter_var($api_base_url, FILTER_VALIDATE_URL)) {
            throw new Exception("رابط API غير صالح");
        }

        $pdo->prepare("INSERT INTO delivery_companies (name, return_fee, api_token, api_base_url) VALUES (?,?,?,?)")
            ->execute([$name, $return_fee, $api_token, $api_base_url]);

        $_SESSION['message'] = "تمت إضافة شركة «{$name}» بنجاح";
        header("Location: companies.php"); exit;
    } catch (Exception $e) { $_SESSION['error_message'] = $e->getMessage(); }
}

// ========== تعديل شركة ==========
if (isset($_POST['update_company'])) {
    try {
        $company_id = (int)$_POST['company_id'];
        $name       = trim($_POST['company_name'] ?? '');
        $return_fee = floatval($_POST['return_fee'] ?? 0);
        $api_token  = trim($_POST['api_token'] ?? '');
        $api_base_url = trim($_POST['api_base_url'] ?? '');

        if (empty($name)) throw new Exception("اسم الشركة مطلوب");
        if (!empty($api_base_url) && !filter_var($api_base_url, FILTER_VALIDATE_URL)) {
            throw new Exception("رابط API غير صالح");
        }

        $pdo->prepare("UPDATE delivery_companies SET name=?, return_fee=?, api_token=?, api_base_url=? WHERE id=?")
            ->execute([$name, $return_fee, $api_token, $api_base_url, $company_id]);

        $_SESSION['message'] = "تم تحديث الشركة بنجاح";
        header("Location: companies.php?company_id={$company_id}"); exit;
    } catch (Exception $e) { $_SESSION['error_message'] = $e->getMessage(); }
}

// ========== حذف شركة ==========
if (isset($_GET['delete_company'])) {
    try {
        $cid = (int)$_GET['delete_company'];
        $pdo->beginTransaction();
        $pdo->prepare("DELETE FROM delivery_prices WHERE delivery_company_id=?")->execute([$cid]);
        $pdo->prepare("DELETE FROM delivery_companies WHERE id=?")->execute([$cid]);
        $pdo->commit();
        $_SESSION['message'] = "تم حذف الشركة بنجاح";
        header("Location: companies.php"); exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error_message'] = $e->getMessage();
    }
}

// ========== تحديث أسعار ==========
if (isset($_POST['update_prices'])) {
    try {
        $pdo->beginTransaction();
        $company_id = (int)$_POST['company_id'];
        $pdo->prepare("DELETE FROM delivery_prices WHERE delivery_company_id=?")->execute([$company_id]);
        $stmt = $pdo->prepare("INSERT INTO delivery_prices (delivery_company_id, wilaya_id, price, delivery_type) VALUES (?,?,?,?)");
        foreach (['home', 'office'] as $type) {
            foreach (($_POST[$type . '_prices'] ?? []) as $wid => $price) {
                if ($price === '' || $price < 0) continue;
                $stmt->execute([$company_id, $wid, floatval($price), $type]);
            }
        }
        $pdo->commit();
        $_SESSION['message'] = "تم حفظ الأسعار بنجاح";
        header("Location: companies.php?company_id={$company_id}"); exit;
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error_message'] = $e->getMessage();
    }
}

// ========== جلب البيانات ==========
$companies = $pdo->query("SELECT * FROM delivery_companies ORDER BY name")->fetchAll();
$wilayas   = $pdo->query("SELECT * FROM wilayas ORDER BY name")->fetchAll();

$selected = null;
$prices   = ['home' => [], 'office' => []];

if (isset($_GET['company_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM delivery_companies WHERE id=?");
    $stmt->execute([(int)$_GET['company_id']]);
    $selected = $stmt->fetch();
    if ($selected) {
        $stmt = $pdo->prepare("SELECT wilaya_id, price, delivery_type FROM delivery_prices WHERE delivery_company_id=?");
        $stmt->execute([$selected['id']]);
        foreach ($stmt->fetchAll() as $p)
            $prices[$p['delivery_type']][$p['wilaya_id']] = $p['price'];
    }
}

$price_counts = [];
foreach ($companies as $co) {
    $s = $pdo->prepare("SELECT COUNT(*) FROM delivery_prices WHERE delivery_company_id=?");
    $s->execute([$co['id']]);
    $price_counts[$co['id']] = (int)$s->fetchColumn();
}
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>إدارة شركات التوصيل</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&display=swap" rel="stylesheet">
<style>
:root{
    --primary:#1E40AF;--primary-l:#3B82F6;--primary-d:#1E3A8A;
    --success:#059669;--success-l:#D1FAE5;
    --danger:#DC2626;--danger-l:#FEE2E2;
    --warning:#D97706;--warning-l:#FEF3C7;
    --info:#0284C7;--info-l:#E0F2FE;
    --purple:#7C3AED;--purple-l:#EDE9FE;
    --bg:#F1F5F9;--surface:#FFF;--surface-2:#F8FAFC;
    --border:#E2E8F0;--text:#0F172A;--text-2:#475569;--text-3:#94A3B8;
    --shadow-sm:0 1px 3px rgba(0,0,0,.06);--shadow-md:0 4px 16px rgba(0,0,0,.08);--shadow-lg:0 10px 40px rgba(0,0,0,.12);
    --r:14px;--rs:8px;--tr:all .22s cubic-bezier(.4,0,.2,1)
}
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box;font-family:'Tajawal',sans-serif}
body{background:var(--bg);color:var(--text);padding:20px;min-height:100vh}
.container{max-width:1300px;margin:0 auto}

.header{display:flex;justify-content:space-between;align-items:center;padding:18px 24px;background:var(--surface);border-radius:var(--r);box-shadow:var(--shadow-sm);border:1px solid var(--border);margin-bottom:22px}
.header h1{color:var(--primary);font-size:20px;font-weight:900;display:flex;align-items:center;gap:10px}
.iw{background:linear-gradient(135deg,var(--primary),var(--primary-l));color:#fff;width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center}

.msg{padding:13px 18px;border-radius:var(--rs);display:flex;align-items:center;gap:10px;font-weight:700;margin-bottom:18px}
.msg-s{background:var(--success-l);color:var(--success);border:1px solid #A7F3D0}
.msg-e{background:var(--danger-l);color:var(--danger);border:1px solid #FECACA}

.card{background:var(--surface);border-radius:var(--r);box-shadow:var(--shadow-sm);border:1px solid var(--border);padding:24px;margin-bottom:20px}
.card-title{font-size:15px;font-weight:900;color:var(--primary);margin-bottom:20px;display:flex;align-items:center;gap:10px;padding-bottom:14px;border-bottom:1.5px solid var(--border)}
.ct-icon{background:linear-gradient(135deg,var(--primary),var(--primary-l));color:#fff;width:30px;height:30px;border-radius:var(--rs);display:flex;align-items:center;justify-content:center;flex-shrink:0}

/* شبكة الشركات */
.cgrid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:14px;margin-bottom:20px}
.ccard{position:relative;background:var(--surface-2);border:1.5px solid var(--border);border-radius:var(--rs);padding:20px 16px 16px;text-align:center;cursor:pointer;transition:var(--tr);text-decoration:none;display:block}
.ccard:hover{border-color:var(--primary-l);box-shadow:var(--shadow-md);transform:translateY(-3px)}
.ccard.active{border-color:var(--primary);background:#EFF6FF;box-shadow:0 0 0 3px rgba(59,130,246,.15)}
.c-icon{width:52px;height:52px;border-radius:50%;background:linear-gradient(135deg,var(--primary),var(--primary-l));color:#fff;display:flex;align-items:center;justify-content:center;font-size:22px;margin:0 auto 10px}
.c-name{font-weight:800;font-size:15px;color:var(--text);margin-bottom:10px}
.badge{display:inline-flex;align-items:center;gap:4px;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:700;margin:2px}
.b-purple{background:var(--purple-l);color:var(--purple);border:1px solid #DDD6FE}
.b-green {background:var(--success-l);color:var(--success);border:1px solid #A7F3D0}
.b-blue  {background:var(--info-l);color:var(--info);border:1px solid #BAE6FD}
.b-warning {background:var(--warning-l);color:var(--warning);border:1px solid #FDE68A}
.b-gray  {background:#F1F5F9;color:#64748B;border:1px solid #CBD5E1}
.btn-del{position:absolute;top:8px;left:8px;width:26px;height:26px;border-radius:50%;background:var(--danger-l);color:var(--danger);border:1px solid #FECACA;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:var(--tr)}
.btn-del:hover{background:var(--danger);color:#fff}

/* نموذج إضافة */
.add-box{background:var(--surface-2);border:1.5px solid var(--border);border-radius:var(--rs);padding:22px}
.add-title{font-size:14px;font-weight:800;color:var(--success);margin-bottom:16px;display:flex;align-items:center;gap:8px}
.g3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px;align-items:end}
.g2{display:grid;grid-template-columns:1fr 1fr;gap:14px}
@media(max-width:700px){.g3,.g2{grid-template-columns:1fr}}

/* تعديل */
.edit-box{background:var(--warning-l);border:1.5px solid #FDE68A;border-radius:var(--rs);padding:20px;margin-bottom:20px}
.edit-title{font-size:13px;font-weight:800;color:var(--warning);margin-bottom:14px}

/* API token & URL fields */
.token-box{background:#EFF6FF;border:1.5px solid #BFDBFE;border-radius:var(--rs);padding:16px;margin-top:14px}
.token-title{font-size:12px;font-weight:800;color:var(--primary);margin-bottom:10px;display:flex;align-items:center;gap:6px}
.pw-wrap{position:relative}
.pw-wrap input{padding-left:42px !important}
.pw-eye{position:absolute;left:12px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;font-size:17px;padding:0;color:var(--text-3);line-height:1}
.api-status{display:inline-flex;align-items:center;gap:5px;padding:5px 12px;border-radius:20px;font-size:12px;font-weight:700;margin-top:8px}
.api-on {background:var(--success-l);color:var(--success);border:1px solid #A7F3D0}
.api-warning {background:var(--warning-l);color:var(--warning);border:1px solid #FDE68A}
.api-off{background:#F1F5F9;color:#64748B;border:1px solid #CBD5E1}

/* table */
.toolbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;flex-wrap:wrap;gap:10px}
.tsearch{padding:9px 14px;border:1.5px solid var(--border);border-radius:var(--rs);font-size:13px;font-family:'Tajawal',sans-serif;width:220px;transition:var(--tr)}
.tsearch:focus{border-color:var(--primary-l);outline:none}
.bin{padding:8px 12px;border:1.5px solid var(--border);border-radius:var(--rs);font-size:13px;font-family:'Tajawal',sans-serif;width:120px}
.tbl-wrap{overflow-x:auto;border-radius:var(--rs);border:1px solid var(--border)}
table.pt{width:100%;border-collapse:collapse;font-size:13px}
table.pt th{background:linear-gradient(135deg,var(--primary),var(--primary-d));color:#fff;padding:12px 14px;text-align:right;font-weight:700;font-size:12px;white-space:nowrap}
table.pt td{padding:10px 14px;border-bottom:1px solid #F1F5F9;vertical-align:middle;color:var(--text-2)}
table.pt tr:last-child td{border-bottom:none}
table.pt tr:hover td{background:#F8FAFC}
.wnum{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;background:var(--primary);color:#fff;border-radius:50%;font-size:11px;font-weight:800;margin-left:8px}
.pf{width:110px;padding:8px 10px;border:1.5px solid var(--border);border-radius:var(--rs);font-size:13px;font-family:'Tajawal',sans-serif;transition:var(--tr);text-align:center}
.pf:focus{border-color:var(--primary-l);outline:none}

/* inputs */
.fg{margin-bottom:0}
.fg label{display:block;margin-bottom:6px;font-weight:700;font-size:13px;color:var(--text)}
.fg small{font-size:11px;color:var(--text-3);margin-top:4px;display:block}
input[type=text],input[type=number],input[type=password],input[type=url],select{width:100%;padding:11px 14px;border:1.5px solid var(--border);border-radius:var(--rs);font-size:14px;transition:var(--tr);font-family:'Tajawal',sans-serif;color:var(--text);background:#fff}
input:focus,select:focus{border-color:var(--primary-l);outline:none;box-shadow:0 0 0 3px rgba(59,130,246,.12)}

/* buttons */
.btn{padding:10px 18px;border-radius:var(--rs);font-weight:700;cursor:pointer;transition:var(--tr);text-decoration:none;display:inline-flex;align-items:center;gap:6px;font-size:13px;border:none;font-family:'Tajawal',sans-serif}
.bp{background:var(--primary);color:#fff}.bp:hover{background:var(--primary-d);transform:translateY(-1px)}
.bs{background:var(--success);color:#fff}.bs:hover{background:#047857;transform:translateY(-1px)}
.bw{background:var(--warning);color:#fff}.bw:hover{background:#B45309;transform:translateY(-1px)}
.bd{background:var(--danger);color:#fff} .bd:hover{background:#B91C1C;transform:translateY(-1px)}
.bg{background:var(--surface-2);color:var(--text-2);border:1.5px solid var(--border)}.bg:hover{background:var(--border)}
.bi{background:var(--info);color:#fff}   .bi:hover{background:#0369A1;transform:translateY(-1px)}
.btn-sm{padding:7px 12px;font-size:12px}
.fa{display:flex;justify-content:flex-end;gap:10px;margin-top:20px;padding-top:16px;border-top:1.5px solid var(--border)}

.empty{text-align:center;padding:50px 20px;color:var(--text-3)}
.empty span{font-size:52px;display:block;margin-bottom:14px;opacity:.5}
.empty p{font-size:15px;font-weight:600}

.modal{display:none;position:fixed;z-index:1000;inset:0;background:rgba(15,23,42,.55);align-items:center;justify-content:center;backdrop-filter:blur(4px);padding:20px}
.modal-c{background:#fff;padding:28px;border-radius:var(--r);width:90%;max-width:420px;box-shadow:var(--shadow-lg)}
.modal-h{display:flex;align-items:center;gap:12px;margin-bottom:14px}
.modal-ic{width:44px;height:44px;border-radius:50%;background:var(--danger-l);color:var(--danger);display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0}
.modal-f{display:flex;justify-content:flex-end;gap:10px;margin-top:20px;padding-top:14px;border-top:1px solid var(--border)}

@media(max-width:768px){body{padding:12px}.header{flex-direction:column;gap:12px}.fa{flex-direction:column}.btn{justify-content:center}}
</style>
</head>
<body>

<button onclick="toggleSidebar()" style="position:fixed;top:15px;right:15px;z-index:900;background:var(--primary);color:#fff;border:none;padding:10px 13px;border-radius:var(--rs);cursor:pointer">
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
<div class="sidebar-overlay" onclick="toggleSidebar()"></div>
<?php include 'sidebar.php'; ?>

<div class="container">

<div class="header">
    <h1>
        <span class="iw">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><rect x="1" y="3" width="15" height="13"/><path d="M16 8h4l3 3v5h-7V8z"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>
        </span>
        إدارة شركات التوصيل
    </h1>
    <a href="index.php" class="btn bg">← رجوع</a>
</div>

<?php if (isset($_SESSION['message'])): ?>
    <div class="msg msg-s">✅ <?= htmlspecialchars($_SESSION['message']) ?></div>
    <?php unset($_SESSION['message']); ?>
<?php endif; ?>
<?php if (isset($_SESSION['error_message'])): ?>
    <div class="msg msg-e">❌ <?= htmlspecialchars($_SESSION['error_message']) ?></div>
    <?php unset($_SESSION['error_message']); ?>
<?php endif; ?>


<!-- ===== قائمة الشركات + إضافة ===== -->
<div class="card">
    <div class="card-title">
        <span class="ct-icon">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 7V5a2 2 0 00-2-2h-4a2 2 0 00-2 2v2"/></svg>
        </span>
        شركات التوصيل
    </div>

    <?php if (!empty($companies)): ?>
    <div class="cgrid">
        <?php foreach ($companies as $co):
            $has_full_api = !empty($co['api_token']) && !empty($co['api_base_url']);
            $has_url_only = empty($co['api_token']) && !empty($co['api_base_url']);
        ?>
        <a href="?company_id=<?= $co['id'] ?>" class="ccard <?= ($selected && $selected['id'] == $co['id']) ? 'active' : '' ?>">
            <button class="btn-del" onclick="event.preventDefault();confirmDel(<?= $co['id'] ?>,'<?= htmlspecialchars($co['name'],ENT_QUOTES) ?>')" title="حذف">
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/></svg>
            </button>
            <div class="c-icon">🚚</div>
            <div class="c-name"><?= htmlspecialchars($co['name']) ?></div>
            <span class="badge b-purple">↩ <?= number_format($co['return_fee'],2) ?> دج</span><br>
            <span class="badge b-green">☰ <?= $price_counts[$co['id']] ?? 0 ?> سعر</span>
            <span class="badge <?= $has_full_api ? 'b-blue' : ($has_url_only ? 'b-warning' : 'b-gray') ?>">
                <?php if ($has_full_api): ?>
                    🔌 API متكامل
                <?php elseif ($has_url_only): ?>
                    🌐 رابط فقط
                <?php else: ?>
                    ⚙️ بدون API
                <?php endif; ?>
            </span>
        </a>
        <?php endforeach; ?>
    </div>
    <?php else: ?>
    <div class="empty"><span>🚛</span><p>لا توجد شركات — أضف شركة أدناه</p></div>
    <?php endif; ?>

    <!-- ===== نموذج إضافة شركة (معدل) ===== -->
    <div class="add-box">
        <div class="add-title">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="16"/><line x1="8" y1="12" x2="16" y2="12"/></svg>
            إضافة شركة توصيل جديدة
        </div>
        <form method="POST">
            <div class="g2" style="margin-bottom:16px">
                <div class="fg">
                    <label>اسم الشركة <span style="color:var(--danger)">*</span></label>
                    <input type="text" name="company_name" placeholder="مثال: ياليدين، Sendex، زاكي..." required>
                </div>
                <div class="fg">
                    <label>رسوم الإرجاع (دج)</label>
                    <input type="number" name="return_fee" value="200" step="0.01" min="0">
                    <small>يُخصم عند إرجاع طلب غير مسلّم</small>
                </div>
            </div>

            <!-- حقل URL الأساسي + API Token معاً -->
            <div class="g2" style="margin-bottom:16px">
                <div class="fg">
                    <label>🔗 رابط API الأساسي <span style="color:var(--text-3)">(اختياري)</span></label>
                    <input type="url" name="api_base_url" 
                           placeholder="https://api.yalidine.com/v1">
                    <small>الرابط الأساسي للـ API (بدون المسارات الفرعية)</small>
                </div>
                <div class="fg">
                    <label>🔑 API Token <span style="color:var(--text-3)">(اختياري)</span></label>
                    <div class="pw-wrap">
                        <input type="password" name="api_token" id="addTok"
                               placeholder="الصق Token الخاص بك">
                        <button type="button" class="pw-eye" onclick="togglePw('addTok',this)">👁</button>
                    </div>
                    <small>مطلوب فقط إذا كان API يتطلب توثيق</small>
                </div>
            </div>

            <div style="margin-top:16px;text-align:left">
                <button type="submit" name="add_company" class="btn bs">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                    إضافة الشركة
                </button>
            </div>
        </form>
    </div>
</div>


<?php if ($selected): 
    $has_full_api = !empty($selected['api_token']) && !empty($selected['api_base_url']);
    $has_url_only = empty($selected['api_token']) && !empty($selected['api_base_url']);
?>

<!-- ===== تعديل الشركة المحددة (معدل) ===== -->
<div class="card">
    <div class="card-title">
        <span class="ct-icon">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
        </span>
        تعديل: <?= htmlspecialchars($selected['name']) ?>
    </div>

    <div class="edit-box">
        <div class="edit-title">✏️ معلومات الشركة</div>
        <form method="POST">
            <input type="hidden" name="company_id"     value="<?= $selected['id'] ?>">
            <input type="hidden" name="update_company" value="1">

            <div class="g2" style="margin-bottom:16px">
                <div class="fg">
                    <label>اسم الشركة</label>
                    <input type="text" name="company_name" value="<?= htmlspecialchars($selected['name']) ?>" required>
                </div>
                <div class="fg">
                    <label>رسوم الإرجاع (دج)</label>
                    <input type="number" name="return_fee" value="<?= $selected['return_fee'] ?>" step="0.01" min="0" required>
                </div>
            </div>

            <!-- حقل URL الأساسي + API Token معاً -->
            <div class="g2" style="margin-bottom:16px">
                <div class="fg">
                    <label>🔗 رابط API الأساسي</label>
                    <input type="url" name="api_base_url" 
                           value="<?= htmlspecialchars($selected['api_base_url'] ?? '') ?>"
                           placeholder="https://api.example.com/v1">
                </div>
                <div class="fg">
                    <label>🔑 API Token</label>
                    <div class="pw-wrap">
                        <input type="password" name="api_token" id="editTok"
                               value="<?= htmlspecialchars($selected['api_token'] ?? '') ?>"
                               placeholder="اتركه فارغاً لإلغاء API">
                        <button type="button" class="pw-eye" onclick="togglePw('editTok',this)">👁</button>
                    </div>
                </div>
            </div>

            <!-- عرض حالة API الحالية -->
            <div class="token-box">
                <div class="token-title">📊 حالة التكامل مع API</div>
                <div style="display:flex;gap:10px;flex-wrap:wrap">
                    <span class="api-status <?= $has_full_api ? 'api-on' : ($has_url_only ? 'api-warning' : 'api-off') ?>">
                        <?php if ($has_full_api): ?>
                            🟢 API متكامل (رابط + Token)
                        <?php elseif ($has_url_only): ?>
                            🟡 رابط فقط (بدون Token)
                        <?php else: ?>
                            ⚫ بدون API
                        <?php endif; ?>
                    </span>
                    
                    <?php if (!empty($selected['api_base_url'])): ?>
                        <span class="api-status b-blue" style="background:#EFF6FF;color:var(--primary);border-color:#BFDBFE">
                            🌐 <?= htmlspecialchars($selected['api_base_url']) ?>
                        </span>
                    <?php endif; ?>
                </div>
            </div>

            <div class="fa">
                <button type="submit" class="btn bw">💾 حفظ التعديلات</button>
            </div>
        </form>
    </div>
</div>


<!-- ===== أسعار التوصيل ===== -->
<div class="card">
    <div class="card-title">
        <span class="ct-icon">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg>
        </span>
        أسعار التوصيل — <?= htmlspecialchars($selected['name']) ?>
    </div>

    <form method="POST" id="pricesForm">
        <input type="hidden" name="company_id" value="<?= $selected['id'] ?>">

        <div class="toolbar">
            <span style="font-size:13px;font-weight:700;color:var(--text-2)">📍 <?= count($wilayas) ?> ولاية</span>
            <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
                <input type="text" class="tsearch" placeholder="🔍 ابحث عن ولاية..." oninput="filterW(this.value)">
                <input type="number" id="bh" class="bin" placeholder="منزل موحد" step="0.01" min="0">
                <button type="button" class="btn bp btn-sm" onclick="bulk('home')">تطبيق 🏠</button>
                <input type="number" id="bo" class="bin" placeholder="مكتب موحد" step="0.01" min="0">
                <button type="button" class="btn bi btn-sm" onclick="bulk('office')">تطبيق 🏢</button>
            </div>
        </div>

        <p style="font-size:12px;color:var(--text-3);margin-bottom:12px">
            ℹ️ اترك الخانة فارغة إذا التوصيل غير متاح لهذه الولاية
        </p>

        <div class="tbl-wrap">
            <table class="pt" id="wt">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>الولاية</th>
                        <th>🏠 سعر المنزل (دج)</th>
                        <th>🏢 سعر المكتب (دج)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($wilayas as $i => $w): ?>
                    <tr data-name="<?= strtolower(htmlspecialchars($w['name'])) ?>">
                        <td><span class="wnum"><?= $i+1 ?></span></td>
                        <td><strong><?= htmlspecialchars($w['name']) ?></strong></td>
                        <td>
                            <input type="number" class="pf hf" name="home_prices[<?= $w['id'] ?>]"
                                step="0.01" min="0" placeholder="—"
                                value="<?= $prices['home'][$w['id']] ?? '' ?>"
                                oninput="cf(this)">
                        </td>
                        <td>
                            <input type="number" class="pf of" name="office_prices[<?= $w['id'] ?>]"
                                step="0.01" min="0" placeholder="—"
                                value="<?= $prices['office'][$w['id']] ?? '' ?>"
                                oninput="cf(this)">
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="fa">
            <a href="companies.php" class="btn bg">إلغاء</a>
            <button type="reset"  class="btn bg">إعادة تعيين</button>
            <button type="submit" name="update_prices" class="btn bs">💾 حفظ الأسعار</button>
        </div>
    </form>
</div>

<?php else: ?>
<div class="card">
    <div class="empty"><span>👆</span><p>اختر شركة من الأعلى لتعديل بياناتها وأسعارها</p></div>
</div>
<?php endif; ?>

</div>

<!-- modal حذف -->
<div id="delModal" class="modal">
    <div class="modal-c">
        <div class="modal-h">
            <div class="modal-ic">⚠️</div>
            <h3 style="font-weight:900;font-size:16px">تأكيد الحذف</h3>
        </div>
        <p id="delMsg" style="color:var(--text-2);font-size:14px;line-height:1.7"></p>
        <div class="modal-f">
            <button class="btn bg" onclick="closeDel()">إلغاء</button>
            <a id="delLink" href="#" class="btn bd">🗑️ حذف نهائياً</a>
        </div>
    </div>
</div>

<script>
function togglePw(id, btn) {
    const i = document.getElementById(id);
    i.type  = i.type === 'password' ? 'text' : 'password';
    btn.textContent = i.type === 'password' ? '👁' : '🙈';
}

function confirmDel(id, name) {
    event.preventDefault();
    document.getElementById('delMsg').textContent = `هل تريد حذف شركة "${name}"؟ سيتم حذف جميع أسعارها.`;
    document.getElementById('delLink').href = '?delete_company=' + id;
    document.getElementById('delModal').style.display = 'flex';
}
function closeDel() { document.getElementById('delModal').style.display = 'none'; }
window.onclick = e => { if (e.target.id === 'delModal') closeDel(); };

function filterW(v) {
    v = v.toLowerCase();
    document.querySelectorAll('#wt tbody tr').forEach(tr => {
        tr.style.display = tr.dataset.name.includes(v) ? '' : 'none';
    });
}

function bulk(type) {
    const val = document.getElementById(type === 'home' ? 'bh' : 'bo').value;
    if (!val) { alert('أدخل قيمة أولاً'); return; }
    document.querySelectorAll('.' + (type === 'home' ? 'h' : 'o') + 'f').forEach(f => {
        if (f.closest('tr').style.display !== 'none') { f.value = val; cf(f); }
    });
}

function cf(f) {
    const v = parseFloat(f.value);
    f.style.borderColor = (!isNaN(v) && v > 0) ? '#A7F3D0' : '';
    f.style.background  = (!isNaN(v) && v > 0) ? '#F0FDF4' : '';
}
document.querySelectorAll('.pf').forEach(f => cf(f));
</script>
</body>
</html>