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

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

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

$delivery_companies = $pdo->query("SELECT * FROM delivery_companies ORDER BY name")->fetchAll();
$wilayas            = $pdo->query("SELECT * FROM wilayas ORDER BY name")->fetchAll();

if (isset($_POST['add_company'])) {
    try {
        $name       = trim($_POST['new_company_name'] ?? '');
        $return_fee = floatval($_POST['return_fee'] ?? 200);
        if (empty($name)) throw new Exception("اسم الشركة مطلوب");
        $pdo->prepare("INSERT INTO delivery_companies (name, return_fee) VALUES (?,?)")->execute([$name, $return_fee]);
        $_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);
        if (empty($name)) throw new Exception("اسم الشركة مطلوب");
        $pdo->prepare("UPDATE delivery_companies SET name=?, return_fee=? WHERE id=?")->execute([$name, $return_fee, $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 {
        $company_id = (int)$_GET['delete_company'];
        $pdo->beginTransaction();
        $pdo->prepare("DELETE FROM delivery_prices WHERE delivery_company_id=?")->execute([$company_id]);
        $pdo->prepare("DELETE FROM delivery_companies WHERE id=?")->execute([$company_id]);
        $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) {
            $key = $type . '_prices';
            if (!empty($_POST[$key])) {
                foreach ($_POST[$key] as $wilaya_id => $price) {
                    if ($price === '' || $price === null) continue;
                    $price = floatval($price);
                    if ($price < 0) continue;
                    $stmt->execute([$company_id, $wilaya_id, $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();
    }
}

$selected_company = null;
$company_prices   = ['home' => [], 'office' => []];

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

$price_counts = [];
foreach ($delivery_companies as $dc) {
    $s = $pdo->prepare("SELECT COUNT(*) FROM delivery_prices WHERE delivery_company_id=?");
    $s->execute([$dc['id']]);
    $price_counts[$dc['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">
     <?php include __DIR__ . '/pwa_head.php'; ?>

<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:#FFFFFF;--surface-2:#F8FAFC;
    --border:#E2E8F0;--text:#0F172A;--text-2:#475569;--text-3:#94A3B8;
    --shadow-sm:0 1px 3px rgba(0,0,0,0.06);--shadow-md:0 4px 16px rgba(0,0,0,0.08);--shadow-lg:0 10px 40px rgba(0,0,0,0.12);
    --radius:14px;--radius-sm:8px;--tr:all 0.22s cubic-bezier(0.4,0,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}
::-webkit-scrollbar{width:5px;height:5px}
::-webkit-scrollbar-track{background:#f1f5f9}
::-webkit-scrollbar-thumb{background:var(--primary-l);border-radius:10px}
.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(--radius);box-shadow:var(--shadow-sm);border:1px solid var(--border);margin-bottom:22px;animation:fadeDown 0.4s ease}
@keyframes fadeDown{from{opacity:0;transform:translateY(-12px)}to{opacity:1;transform:translateY(0)}}
.header h1{color:var(--primary);font-size:20px;font-weight:900;display:flex;align-items:center;gap:10px}
.icon-wrap{background:linear-gradient(135deg,var(--primary),var(--primary-l));color:white;width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center}

.msg{padding:13px 18px;border-radius:var(--radius-sm);display:flex;align-items:center;gap:10px;font-weight:600;margin-bottom:18px;animation:slideIn 0.3s ease}
@keyframes slideIn{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}
.msg-success{background:var(--success-l);color:var(--success);border:1px solid #A7F3D0}
.msg-error  {background:var(--danger-l);color:var(--danger);border:1px solid #FECACA}

.card{background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow-sm);border:1px solid var(--border);padding:24px;margin-bottom:20px;animation:fadeUp 0.4s ease both}
@keyframes fadeUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
.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)}
.card-title .ct-icon{background:linear-gradient(135deg,var(--primary),var(--primary-l));color:white;width:30px;height:30px;border-radius:var(--radius-sm);display:flex;align-items:center;justify-content:center;flex-shrink:0}

.company-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:14px;margin-bottom:20px}
.company-card{position:relative;background:var(--surface-2);border:1.5px solid var(--border);border-radius:var(--radius-sm);padding:20px 16px 16px;text-align:center;cursor:pointer;transition:var(--tr);text-decoration:none;display:block}
.company-card:hover{border-color:var(--primary-l);box-shadow:var(--shadow-md);transform:translateY(-3px)}
.company-card.active{border-color:var(--primary);background:#EFF6FF;box-shadow:0 0 0 3px rgba(59,130,246,0.15)}
.company-card .c-icon{width:54px;height:54px;border-radius:50%;background:linear-gradient(135deg,var(--primary),var(--primary-l));color:white;display:flex;align-items:center;justify-content:center;font-size:24px;margin:0 auto 12px;transition:var(--tr)}
.company-card.active .c-icon{background:linear-gradient(135deg,var(--primary-d),var(--primary))}
.company-card .c-name{font-weight:800;font-size:15px;color:var(--text);margin-bottom:8px}
.return-fee-badge{display:inline-flex;align-items:center;gap:5px;background:var(--purple-l);color:var(--purple);padding:4px 10px;border-radius:20px;font-size:11px;font-weight:700;border:1px solid #DDD6FE;margin-bottom:8px}
.prices-count-badge{display:inline-flex;align-items:center;gap:4px;background:var(--success-l);color:var(--success);padding:3px 8px;border-radius:20px;font-size:11px;font-weight:700;border:1px solid #A7F3D0}
.btn-delete-card{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-delete-card:hover{background:var(--danger);color:white}

.add-form-box{background:var(--surface-2);border:1.5px solid var(--border);border-radius:var(--radius-sm);padding:20px}
.add-form-box h4{font-size:14px;font-weight:800;color:var(--primary);margin-bottom:14px;display:flex;align-items:center;gap:8px}
.form-row-3{display:grid;grid-template-columns:1fr 1fr auto;gap:14px;align-items:end}
@media(max-width:600px){.form-row-3{grid-template-columns:1fr}}
.form-row-2{display:grid;grid-template-columns:1fr 1fr;gap:14px}
@media(max-width:600px){.form-row-2{grid-template-columns:1fr}}

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

.company-info-bar{background:linear-gradient(135deg,#EFF6FF,#E0F2FE);border:1.5px solid #BFDBFE;border-radius:var(--radius-sm);padding:16px 20px;margin-bottom:20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px}
.company-info-bar .cib-left{display:flex;align-items:center;gap:14px}
.company-info-bar .cib-icon{width:46px;height:46px;border-radius:50%;background:linear-gradient(135deg,var(--primary),var(--primary-l));color:white;display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0}
.company-info-bar h3{font-size:16px;font-weight:900;color:var(--primary);margin-bottom:3px}
.company-info-bar p{font-size:12px;color:var(--text-2)}

.edit-company-box{background:var(--warning-l);border:1.5px solid #FDE68A;border-radius:var(--radius-sm);padding:16px 20px;margin-bottom:20px}
.edit-company-box h4{font-size:13px;font-weight:800;color:var(--warning);margin-bottom:12px;display:flex;align-items:center;gap:7px}
.edit-form-inline{display:flex;gap:12px;align-items:end;flex-wrap:wrap}
.edit-form-inline .form-group{flex:1;min-width:160px}

.table-toolbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;flex-wrap:wrap;gap:10px}
.table-toolbar h4{font-size:14px;font-weight:800;color:var(--text);display:flex;align-items:center;gap:7px}
.table-search{padding:9px 14px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:13px;font-family:'Tajawal',sans-serif;width:220px;transition:var(--tr)}
.table-search:focus{border-color:var(--primary-l);outline:none;box-shadow:0 0 0 3px rgba(59,130,246,0.12)}
.bulk-btns{display:flex;gap:8px;flex-wrap:wrap}
.bulk-input{padding:8px 12px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:13px;font-family:'Tajawal',sans-serif;width:110px}
.bulk-input:focus{border-color:var(--primary-l);outline:none}

.table-responsive{overflow-x:auto;border-radius:var(--radius-sm);border:1px solid var(--border)}
table.prices-tbl{width:100%;border-collapse:collapse;font-size:13px}
table.prices-tbl th{background:linear-gradient(135deg,var(--primary),var(--primary-d));color:white;padding:12px 14px;text-align:right;font-weight:700;font-size:12px;white-space:nowrap}
table.prices-tbl td{padding:10px 14px;border-bottom:1px solid #F1F5F9;vertical-align:middle;color:var(--text-2)}
table.prices-tbl tr:last-child td{border-bottom:none}
table.prices-tbl tr:hover td{background:#F8FAFC}
table.prices-tbl td:first-child{font-weight:700;color:var(--text)}
.price-field{width:110px;padding:8px 10px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:13px;font-family:'Tajawal',sans-serif;transition:var(--tr);text-align:center}
.price-field:focus{border-color:var(--primary-l);outline:none;box-shadow:0 0 0 2px rgba(59,130,246,0.1)}
.wilaya-num{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;background:var(--primary);color:white;border-radius:50%;font-size:11px;font-weight:800;margin-left:8px;flex-shrink:0}

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

.btn{padding:10px 18px;border-radius:var(--radius-sm);font-weight:700;cursor:pointer;transition:var(--tr);text-decoration:none;display:inline-flex;align-items:center;gap:6px;font-size:13px;border:none}
.btn-primary      {background:var(--primary);color:white}
.btn-primary:hover{background:var(--primary-d);transform:translateY(-1px);box-shadow:0 4px 14px rgba(30,64,175,0.3)}
.btn-success      {background:var(--success);color:white}
.btn-success:hover{background:#047857;transform:translateY(-1px)}
.btn-warning      {background:var(--warning);color:white}
.btn-warning:hover{background:#B45309;transform:translateY(-1px)}
.btn-danger       {background:var(--danger);color:white}
.btn-danger:hover {background:#B91C1C;transform:translateY(-1px)}
.btn-gray         {background:var(--surface-2);color:var(--text-2);border:1.5px solid var(--border)}
.btn-gray:hover   {background:var(--border)}
.btn-info         {background:var(--info);color:white}
.btn-info:hover   {background:#0369A1;transform:translateY(-1px)}
.btn-sm{padding:7px 12px;font-size:12px}
.form-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:20px;padding-top:16px;border-top:1.5px solid var(--border)}

.modal{display:none;position:fixed;z-index:1000;inset:0;background:rgba(15,23,42,0.55);align-items:center;justify-content:center;backdrop-filter:blur(4px);padding:20px}
.modal-content{background:white;padding:28px;border-radius:var(--radius);width:90%;max-width:440px;box-shadow:var(--shadow-lg);animation:modalIn 0.25s ease}
@keyframes modalIn{from{opacity:0;transform:scale(0.96) translateY(-10px)}to{opacity:1;transform:scale(1) translateY(0)}}
.modal-header{display:flex;align-items:center;gap:12px;margin-bottom:16px}
.modal-icon{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-header h3{font-size:16px;font-weight:900;color:var(--text)}
.modal-footer{display:flex;justify-content:flex-end;gap:10px;margin-top:22px;padding-top:16px;border-top:1px solid var(--border)}

@media(max-width:768px){
    body{padding:12px}
    .header{flex-direction:column;align-items:flex-start;gap:12px}
    .company-info-bar{flex-direction:column;align-items:flex-start}
    .edit-form-inline{flex-direction:column}
    .form-actions{flex-direction:column}
    .btn{justify-content:center}
}
</style>
    <?php include __DIR__ . '/darkmode.php'; ?>
</head>
<body>

<button onclick="toggleSidebar()" style="position:fixed;top:15px;right:15px;z-index:900;background:var(--primary);color:white;border:none;padding:10px 13px;border-radius:var(--radius-sm);cursor:pointer;display:flex;align-items:center" title="القائمة">
    <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">

    <!-- HEADER -->
    <div class="header">
        <h1>
            <span class="icon-wrap">
                <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 btn-gray">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="9 18 3 12 9 6"/><line x1="3" y1="12" x2="21" y2="12"/></svg>
            رجوع
        </a>
    </div>

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

    <!-- ===== الشركات ===== -->
    <div class="card" style="animation-delay:0.05s">
        <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"/><line x1="12" y1="12" x2="12" y2="16"/><line x1="10" y1="14" x2="14" y2="14"/></svg>
            </span>
            شركات التوصيل المتاحة
        </div>

        <?php if (!empty($delivery_companies)): ?>
        <div class="company-grid">
            <?php foreach ($delivery_companies as $dc): ?>
            <a href="?company_id=<?= $dc['id'] ?>" class="company-card <?= ($selected_company && $selected_company['id'] == $dc['id']) ? 'active' : '' ?>">
                <button class="btn-delete-card" onclick="event.preventDefault(); confirmDelete(<?= $dc['id'] ?>, '<?= htmlspecialchars($dc['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"/><path d="M10 11v6M14 11v6"/></svg>
                </button>
                <div class="c-icon">🚚</div>
                <div class="c-name"><?= htmlspecialchars($dc['name']) ?></div>
                <div class="return-fee-badge">
                    ↩ رسوم الإرجاع: <?= number_format($dc['return_fee'], 2) ?> دج
                </div>
                <div>
                    <span class="prices-count-badge">
                        ☰ <?= $price_counts[$dc['id']] ?? 0 ?> سعر
                    </span>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="empty-state">
            <span class="es-icon">🚛</span>
            <p>لا توجد شركات توصيل — أضف شركة أدناه</p>
        </div>
        <?php endif; ?>

        <!-- إضافة شركة جديدة -->
        <div class="add-form-box">
            <h4>
                <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>
                إضافة شركة توصيل جديدة
            </h4>
            <form method="POST">
                <div class="form-row-3">
                    <div class="form-group">
                        <label>اسم الشركة <span style="color:var(--danger)">*</span></label>
                        <input type="text" name="new_company_name" placeholder="مثال: ياليدين، زاكي..." required>
                    </div>
                    <div class="form-group">
                        <label>رسوم الإرجاع (دج)</label>
                        <input type="number" name="return_fee" value="200" step="0.01" min="0">
                        <small>المبلغ عند إرجاع الطلب غير المسلّم</small>
                    </div>
                    <div>
                        <button type="submit" name="add_company" class="btn btn-success" style="width:100%">
                            <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>
                </div>
            </form>
        </div>
    </div>

    <?php if ($selected_company): ?>

    <!-- ===== تعديل بيانات الشركة ===== -->
    <div class="card" style="animation-delay:0.1s">
        <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>
            تعديل بيانات الشركة
        </div>

        <div class="company-info-bar">
            <div class="cib-left">
                <div class="cib-icon">🚚</div>
                <div>
                    <h3><?= htmlspecialchars($selected_company['name']) ?></h3>
                    <p>
                        <span class="return-fee-badge" style="font-size:12px">↩ رسوم الإرجاع: <?= number_format($selected_company['return_fee'], 2) ?> دج</span>
                        &nbsp;
                        <span class="prices-count-badge" style="font-size:12px">☰ <?= $price_counts[$selected_company['id']] ?? 0 ?> سعر مسجّل</span>
                    </p>
                </div>
            </div>
        </div>

        <div class="edit-company-box">
            <h4>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--warning)" stroke-width="2.5"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 013 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
                تعديل اسم الشركة ورسوم الإرجاع
            </h4>
            <form method="POST">
                <input type="hidden" name="company_id" value="<?= $selected_company['id'] ?>">
                <input type="hidden" name="update_company" value="1">
                <div class="edit-form-inline">
                    <div class="form-group">
                        <label>اسم الشركة</label>
                        <input type="text" name="company_name" value="<?= htmlspecialchars($selected_company['name']) ?>" required>
                    </div>
                    <div class="form-group">
                        <label>رسوم الإرجاع (دج)</label>
                        <input type="number" name="return_fee" value="<?= $selected_company['return_fee'] ?>" step="0.01" min="0" required>
                    </div>
                    <div>
                        <button type="submit" class="btn btn-warning">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/></svg>
                            حفظ التعديل
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- ===== أسعار التوصيل ===== -->
    <div class="card" style="animation-delay:0.15s">
        <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_company['name']) ?>
        </div>

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

            <div class="table-toolbar">
                <h4>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2.5"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z"/><circle cx="12" cy="10" r="3"/></svg>
                    <?= count($wilayas) ?> ولاية
                </h4>
                <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
                    <input type="text" class="table-search" id="wilayaSearch" placeholder="🔍 ابحث عن ولاية..." oninput="filterWilayas(this.value)">
                    <div class="bulk-btns">
                        <input type="number" id="bulkHomeVal" class="bulk-input" placeholder="منزل موحد" step="0.01" min="0">
                        <button type="button" class="btn btn-primary btn-sm" onclick="applyBulk('home')">
                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></svg>
                            تطبيق على الكل
                        </button>
                        <input type="number" id="bulkOfficeVal" class="bulk-input" placeholder="مكتب موحد" step="0.01" min="0">
                        <button type="button" class="btn btn-info btn-sm" onclick="applyBulk('office')">
                            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" 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>
                            تطبيق على الكل
                        </button>
                    </div>
                </div>
            </div>

            <p style="font-size:12px;color:var(--text-3);margin-bottom:12px;display:flex;align-items:center;gap:5px">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
                اترك الخانة فارغة إذا لم يكن التوصيل متاحاً لهذه الولاية
            </p>

            <div class="table-responsive">
                <table class="prices-tbl" id="wilayasTable">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>الولاية</th>
                            <th>
                                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:middle;margin-left:4px"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></svg>
                                سعر المنزل (دج)
                            </th>
                            <th>
                                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:middle;margin-left:4px"><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>
                                سعر المكتب (دج)
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($wilayas as $i => $w): ?>
                        <tr data-name="<?= htmlspecialchars(strtolower($w['name'])) ?>">
                            <td><span class="wilaya-num"><?= $i + 1 ?></span></td>
                            <td><strong><?= htmlspecialchars($w['name']) ?></strong></td>
                            <td>
                                <input type="number" class="price-field home-field"
                                    name="home_prices[<?= $w['id'] ?>]"
                                    step="0.01" min="0" placeholder="—"
                                    value="<?= isset($company_prices['home'][$w['id']]) ? htmlspecialchars($company_prices['home'][$w['id']]) : '' ?>"
                                    oninput="colorField(this)">
                            </td>
                            <td>
                                <input type="number" class="price-field office-field"
                                    name="office_prices[<?= $w['id'] ?>]"
                                    step="0.01" min="0" placeholder="—"
                                    value="<?= isset($company_prices['office'][$w['id']]) ? htmlspecialchars($company_prices['office'][$w['id']]) : '' ?>"
                                    oninput="colorField(this)">
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="form-actions">
                <a href="companies.php" class="btn btn-gray">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                    إلغاء
                </a>
                <button type="reset" class="btn btn-gray">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 102.13-9.36L1 10"/></svg>
                    إعادة تعيين
                </button>
                <button type="submit" name="update_prices" class="btn btn-success">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/></svg>
                    حفظ أسعار التوصيل
                </button>
            </div>
        </form>
    </div>

    <?php else: ?>
    <div class="card" style="animation-delay:0.1s">
        <div class="empty-state">
            <span class="es-icon">👆</span>
            <p>اختر شركة توصيل من الأعلى لعرض وتعديل أسعارها</p>
        </div>
    </div>
    <?php endif; ?>

</div><!-- /container -->

<!-- MODAL حذف -->
<div id="deleteModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <div class="modal-icon">⚠️</div>
            <h3>تأكيد حذف الشركة</h3>
        </div>
        <p id="deleteMsg" style="color:var(--text-2);font-size:14px;line-height:1.7"></p>
        <div class="modal-footer">
            <button class="btn btn-gray" onclick="closeModal()">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                إلغاء
            </button>
            <a id="deleteLink" href="#" class="btn btn-danger">
                <svg width="13" height="13" 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"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2"/></svg>
                حذف نهائياً
            </a>
        </div>
    </div>
</div>

<script>
function confirmDelete(id, name) {
    event.preventDefault();
    document.getElementById('deleteMsg').textContent = `هل أنت متأكد من حذف شركة "${name}"؟ سيتم حذف جميع أسعار التوصيل المرتبطة بها نهائياً.`;
    document.getElementById('deleteLink').href = '?delete_company=' + id;
    document.getElementById('deleteModal').style.display = 'flex';
}
function closeModal() { document.getElementById('deleteModal').style.display = 'none'; }
window.onclick = e => { if (e.target.id === 'deleteModal') closeModal(); };

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

function applyBulk(type) {
    const val = document.getElementById('bulk' + (type === 'home' ? 'Home' : 'Office') + 'Val').value;
    if (val === '') { alert('أدخل قيمة أولاً'); return; }
    document.querySelectorAll('.' + type + '-field').forEach(f => {
        if (f.closest('tr').style.display !== 'none') { f.value = val; colorField(f); }
    });
}

function colorField(input) {
    const v = parseFloat(input.value);
    if (!isNaN(v) && v > 0) { input.style.borderColor = '#A7F3D0'; input.style.background = '#F0FDF4'; }
    else { input.style.borderColor = ''; input.style.background = ''; }
}

document.querySelectorAll('.price-field').forEach(f => colorField(f));
</script>
</body>
</html>