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

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

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';

function sendMail($to, $subject, $message) {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'imadallouache110@gmail.com';
        $mail->Password   = 'qtgp sfff biuy xoax';
        $mail->SMTPSecure = 'tls';
        $mail->Port       = 587;
        $mail->CharSet    = 'UTF-8';
        $mail->setFrom('imadallouache110@gmail.com', 'لوحة التحكم');
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $message;
        $mail->send();
        return true;
    } catch (Exception $e) {
        error_log("Mail Error: " . $mail->ErrorInfo);
        return false;
    }
}

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

if (!isset($_SESSION['user']['id'])) {
    header("Location: login.php"); exit();
}

$admin = $pdo->prepare("SELECT * FROM admin WHERE id=?");
$admin->execute([$_SESSION['user']['id']]);
$settings = $admin->fetch();
if (!$settings) { header("Location: login.php"); exit(); }

$store_settings = $pdo->query("SELECT * FROM stores WHERE id=1")->fetch();
$admins = $pdo->query("SELECT * FROM admin ORDER BY id")->fetchAll();

$pending_invites = $pdo->query(
    "SELECT * FROM admin_invitations WHERE used=0 AND expiry > NOW() ORDER BY created_at DESC"
)->fetchAll();
$pdo->exec("DELETE FROM admin_invitations WHERE expiry <= NOW()");

function isValidEmail(string $email): bool {
    if (empty($email)) return false;
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
    $parts = explode('@', $email);
    if (count($parts) !== 2) return false;
    $domain = $parts[1];
    if (strpos($domain, '.') === false) return false;
    $tld = substr($domain, strrpos($domain, '.') + 1);
    if (strlen($tld) < 2) return false;
    if (preg_match('/^[.\-]|[.\-]$/', $domain)) return false;
    return true;
}

// ══════════════════════════════════════════════
//  تحديث الإعدادات العامة
// ══════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_settings'])) {
    try {
        $name        = trim($_POST['name']        ?? '');
        $description = trim($_POST['description'] ?? '');
        $email       = strtolower(trim($_POST['email'] ?? ''));
        $phone       = trim($_POST['phone']       ?? '');
        $facebook    = trim($_POST['facebook']    ?? '');
        $telegram    = trim($_POST['telegram']    ?? '');
        $instagram   = trim($_POST['instagram']   ?? '');
        $emailp      = strtolower(trim($_POST['emailp'] ?? ''));
        $meta_pixel_enabled = isset($_POST['meta_pixel_enabled']) ? 1 : 0;
        $meta_pixel_id      = preg_replace('/[^0-9]/', '', trim($_POST['meta_pixel_id'] ?? ''));

        if (!empty($name) || !empty($email) || !empty($phone)) {
            if (empty($name))  throw new Exception("اسم المتجر مطلوب.");
            if (empty($phone)) throw new Exception("رقم الهاتف مطلوب.");
            if (empty($email)) throw new Exception("البريد الإلكتروني للدخول مطلوب.");
            if (!isValidEmail($email))
                throw new Exception("بريد الدخول غير صالح — مثال: name@domain.com");
            if (!empty($emailp) && !isValidEmail($emailp))
                throw new Exception("بريد التواصل مع العملاء غير صالح — مثال: support@domain.com");
        }

        $logo = $store_settings['logo'] ?? '';
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] == UPLOAD_ERR_OK) {
            $file = $_FILES['logo'];
            $uploadDir = 'Uploads/logos/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
            $fileName = uniqid() . '_' . basename($file['name']);
            if (move_uploaded_file($file['tmp_name'], $uploadDir . $fileName)) {
                if (!empty($store_settings['logo']) && file_exists($store_settings['logo'])) @unlink($store_settings['logo']);
                $logo = $uploadDir . $fileName;
            }
        }

        $pdo->beginTransaction();
        if (!empty($email))
            $pdo->prepare("UPDATE admin SET email=? WHERE id=?")->execute([$email, $_SESSION['user']['id']]);
        $pdo->prepare("UPDATE stores SET name=?,description=?,logo=?,phone=?,facebook=?,telegram=?,instgrame=?,emailp=?,meta_pixel_id=?,meta_pixel_enabled=? WHERE id=1")
            ->execute([$name?:$store_settings['name'],$description?:$store_settings['description'],$logo?:$store_settings['logo'],$phone?:$store_settings['phone'],$facebook?:$store_settings['facebook'],$telegram?:$store_settings['telegram'],$instagram?:$store_settings['instgrame'],$emailp?:$store_settings['emailp'],$meta_pixel_id,$meta_pixel_enabled]);
        $pdo->commit();
        $_SESSION['message'] = "تم حفظ الإعدادات بنجاح";
        header("Location: settings.php"); exit();
    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $_SESSION['error'] = $e->getMessage();
        header("Location: settings.php"); exit();
    }
}

// ══════════════════════════════════════════════
//  تغيير كلمة المرور
// ══════════════════════════════════════════════
if (isset($_POST['change_password'])) {
    try {
        $current = $_POST['current_password'] ?? '';
        $new     = $_POST['new_password']     ?? '';
        $confirm = $_POST['confirm_password'] ?? '';
        if (empty($current)||empty($new)||empty($confirm)) throw new Exception("يرجى ملء جميع الحقول");
        if (!password_verify($current, $settings['password'])) throw new Exception("كلمة المرور الحالية غير صحيحة");
        if ($new !== $confirm) throw new Exception("كلمة المرور الجديدة غير متطابقة");
        if (strlen($new) < 8) throw new Exception("كلمة المرور يجب أن تكون 8 أحرف على الأقل");
        $pdo->prepare("UPDATE admin SET password=? WHERE id=?")->execute([password_hash($new, PASSWORD_DEFAULT), $_SESSION['user']['id']]);
        $_SESSION['message'] = "تم تغيير كلمة المرور بنجاح";
    } catch (Exception $e) { $_SESSION['error'] = $e->getMessage(); }
    header("Location: settings.php"); exit();
}

// ══════════════════════════════════════════════
//  تفعيل/تعطيل السلة
// ══════════════════════════════════════════════
if (isset($_POST['update_cart'])) {
    $cart_enabled = isset($_POST['cart_enabled']) ? 1 : 0;
    $pdo->prepare("UPDATE stores SET cart_enabled=? WHERE id=1")->execute([$cart_enabled]);
    $_SESSION['message'] = $cart_enabled ? "✅ تم تفعيل سلة التسوق" : "⛔ تم تعطيل سلة التسوق";
    header("Location: settings.php?tab=cart"); exit();
}

// ══════════════════════════════════════════════
//  دعوة أدمين
// ══════════════════════════════════════════════
if (isset($_POST['invite_admin'])) {
    try {
        $inv_email = strtolower(trim($_POST['invite_email'] ?? ''));
        if (empty($inv_email)) throw new Exception("يرجى إدخال البريد الإلكتروني.");
        if (!isValidEmail($inv_email)) throw new Exception("البريد الإلكتروني غير صالح.");
        $check = $pdo->prepare("SELECT COUNT(*) FROM admin WHERE email=?");
        $check->execute([$inv_email]);
        if ($check->fetchColumn() > 0) throw new Exception("هذا البريد الإلكتروني مسجل مسبقاً.");
        $pdo->prepare("DELETE FROM admin_invitations WHERE email=?")->execute([$inv_email]);
        $token  = bin2hex(random_bytes(32));
        $expiry = date('Y-m-d H:i:s', strtotime('+24 hours'));
        $pdo->prepare("INSERT INTO admin_invitations (email, token, expiry) VALUES (?, ?, ?)")->execute([$inv_email, $token, $expiry]);
        $link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on' ? 'https' : 'http')
              . '://' . $_SERVER['HTTP_HOST']
              . dirname($_SERVER['PHP_SELF'])
              . '/activate.php?token=' . $token;
        $subject = 'دعوة للانضمام كمسؤول في لوحة التحكم';
        $body = '<div dir="rtl" style="font-family:Arial,sans-serif;max-width:520px;margin:0 auto;background:#f8fafc;padding:30px;border-radius:12px">
            <div style="background:linear-gradient(135deg,#1E40AF,#3B82F6);border-radius:10px;padding:24px;text-align:center;margin-bottom:24px">
                <h1 style="color:white;margin:0;font-size:20px">🛡️ دعوة مسؤول جديد</h1>
            </div>
            <div style="background:white;border-radius:10px;padding:24px;border:1px solid #e2e8f0">
                <p style="color:#334155;font-size:15px;margin-bottom:16px">مرحباً،</p>
                <p style="color:#334155;font-size:14px;line-height:1.7;margin-bottom:20px">تمت دعوتك للانضمام كمسؤول في لوحة تحكم المتجر.</p>
                <div style="text-align:center;margin:24px 0">
                    <a href="' . htmlspecialchars($link) . '" style="background:linear-gradient(135deg,#1E40AF,#3B82F6);color:white;padding:14px 32px;border-radius:8px;text-decoration:none;font-size:15px;font-weight:bold;display:inline-block">✅ تفعيل الحساب</a>
                </div>
                <div style="background:#FEF3C7;border:1px solid #FDE68A;border-radius:8px;padding:12px 16px;margin-top:16px">
                    <p style="color:#92400E;font-size:12px;margin:0">⏰ <strong>تنبيه:</strong> هذا الرابط صالح لمدة 24 ساعة فقط.</p>
                </div>
            </div>
        </div>';
        $sent = sendMail($inv_email, $subject, $body);
        if ($sent) { $_SESSION['message'] = "تم إرسال الدعوة إلى: {$inv_email}"; }
        else { $pdo->prepare("DELETE FROM admin_invitations WHERE token=?")->execute([$token]); throw new Exception("فشل إرسال الإيميل."); }
    } catch (Exception $e) { $_SESSION['error'] = $e->getMessage(); }
    header("Location: settings.php?tab=admins"); exit();
}

// ══════════════════════════════════════════════
//  إلغاء دعوة / حذف أدمين
// ══════════════════════════════════════════════
if (isset($_POST['cancel_invite'])) {
    $pdo->prepare("DELETE FROM admin_invitations WHERE id=? AND used=0")->execute([(int)$_POST['invite_id']]);
    $_SESSION['message'] = "تم إلغاء الدعوة.";
    header("Location: settings.php?tab=admins"); exit();
}
if (isset($_POST['delete_admin'])) {
    try {
        $del_id = (int)$_POST['admin_id'];
        if ($del_id === (int)$_SESSION['user']['id']) throw new Exception("لا يمكنك حذف حسابك الخاص");
        $pdo->prepare("DELETE FROM admin WHERE id=?")->execute([$del_id]);
        $_SESSION['message'] = "تم حذف المسؤول بنجاح";
    } catch (Exception $e) { $_SESSION['error'] = $e->getMessage(); }
    header("Location: settings.php?tab=admins"); exit();
}

$active_tab = $_GET['tab'] ?? 'general';
?>
<!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;
    --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);
    --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}
.container{max-width:900px;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 .4s ease;flex-wrap:wrap;gap:12px}
@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 .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}

.tabs-wrapper{background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow-sm);border:1px solid var(--border);overflow:hidden;animation:fadeUp .4s ease .1s both}
@keyframes fadeUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
.tabs-nav{display:flex;border-bottom:1.5px solid var(--border);overflow-x:auto;background:var(--surface-2)}
.tab-btn{padding:14px 20px;cursor:pointer;font-size:13px;font-weight:700;color:var(--text-3);border:none;background:none;border-bottom:3px solid transparent;transition:var(--tr);white-space:nowrap;display:flex;align-items:center;gap:7px}
.tab-btn:hover{color:var(--primary);background:rgba(59,130,246,.05)}
.tab-btn.active{color:var(--primary);border-bottom-color:var(--primary);background:var(--surface)}
.tab-btn .ti{width:26px;height:26px;border-radius:var(--radius-sm);display:flex;align-items:center;justify-content:center;transition:var(--tr)}
.tab-btn.active .ti{background:linear-gradient(135deg,var(--primary),var(--primary-l));color:white}
.tab-btn:not(.active) .ti{background:var(--border);color:var(--text-3)}

.tab-pane{display:none;padding:28px}
.tab-pane.active{display:block;animation:fadeUp .3s ease}

.section-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)}
.section-title .st-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}

.form-group{margin-bottom:18px}
.form-group label{display:block;margin-bottom:7px;font-weight:700;font-size:13px;color:var(--text)}
.form-group label .req{color:var(--danger);margin-right:3px}
.form-group label .opt{color:var(--text-3);font-weight:400;font-size:11px}
input[type=text],input[type=email],input[type=tel],input[type=url],input[type=password],select,textarea{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,textarea:focus{border-color:var(--primary-l);outline:none;box-shadow:0 0 0 3px rgba(59,130,246,.12)}
input.ok {border-color:var(--success)!important;background:#F0FDF4!important}
input.err{border-color:var(--danger)!important;background:#FFF5F5!important}
textarea{min-height:100px;resize:vertical}
.form-row-2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media(max-width:600px){.form-row-2{grid-template-columns:1fr}}
.field-note{font-size:11px;margin-top:5px;display:block;font-weight:700}
.field-note.ok {color:var(--success)}
.field-note.err{color:var(--danger)}
.field-note.hint{color:var(--text-3);font-weight:400}

.pass-rules{background:var(--surface-2);border:1.5px solid var(--border);border-radius:var(--radius-sm);padding:12px 14px;margin-top:8px;display:none}
.pass-rules.show{display:block}
.rule{display:flex;align-items:center;gap:7px;font-size:12px;color:var(--text-3);margin-bottom:5px;transition:var(--tr)}
.rule:last-child{margin-bottom:0}
.rule.ok{color:var(--success)}
.rule .dot{width:8px;height:8px;border-radius:50%;background:var(--text-3);flex-shrink:0;transition:var(--tr)}
.rule.ok .dot{background:var(--success)}

.logo-area{display:flex;align-items:center;gap:20px;padding:16px;background:var(--surface-2);border-radius:var(--radius-sm);border:1.5px solid var(--border);margin-bottom:18px}
.logo-box{width:90px;height:90px;border-radius:var(--radius-sm);border:2px dashed var(--border);display:flex;align-items:center;justify-content:center;overflow:hidden;background:white;flex-shrink:0}
.logo-box img{width:100%;height:100%;object-fit:contain}
.logo-box .no-logo{font-size:28px;color:var(--text-3)}
.logo-info h4{font-size:13px;font-weight:800;color:var(--text);margin-bottom:4px}
.logo-info p{font-size:12px;color:var(--text-3);margin-bottom:10px}
.logo-file{display:none}
.btn-choose{padding:8px 14px;background:var(--surface);border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:12px;font-weight:700;cursor:pointer;transition:var(--tr);color:var(--text-2);display:inline-flex;align-items:center;gap:6px}
.btn-choose:hover{border-color:var(--primary-l);color:var(--primary);background:#EFF6FF}

.toggle-row{display:flex;align-items:center;justify-content:space-between;padding:14px 16px;background:var(--surface-2);border-radius:var(--radius-sm);border:1.5px solid var(--border);margin-bottom:18px}
.toggle-info h4{font-size:14px;font-weight:700;color:var(--text)}
.toggle-info p{font-size:12px;color:var(--text-3);margin-top:2px}
.switch{position:relative;display:inline-block;width:52px;height:28px;flex-shrink:0}
.switch input{opacity:0;width:0;height:0}
.slider{position:absolute;cursor:pointer;inset:0;background:#CBD5E1;transition:var(--tr);border-radius:34px}
.slider:before{position:absolute;content:'';height:20px;width:20px;left:4px;bottom:4px;background:white;transition:var(--tr);border-radius:50%;box-shadow:0 1px 4px rgba(0,0,0,.2)}
input:checked+.slider{background:var(--primary)}
input:checked+.slider:before{transform:translateX(24px)}

.pixel-info{background:linear-gradient(135deg,#EFF6FF,#E0F2FE);border:1.5px solid #BFDBFE;border-radius:var(--radius-sm);padding:16px;margin-bottom:20px}
.pixel-info h4{font-size:14px;font-weight:800;color:var(--primary);margin-bottom:6px;display:flex;align-items:center;gap:8px}
.pixel-info p{font-size:12px;color:var(--text-2);line-height:1.7}
.pixel-info a{color:var(--primary);font-weight:700}

/* ─── بطاقة حالة السلة ─── */
.cart-status-card{
    border-radius:var(--radius);padding:28px;text-align:center;margin-bottom:28px;
    transition:var(--tr);
}
.cart-status-card.enabled{
    background:linear-gradient(135deg,#D1FAE5,#A7F3D0);
    border:2px solid #6EE7B7;
}
.cart-status-card.disabled{
    background:linear-gradient(135deg,#F1F5F9,#E2E8F0);
    border:2px solid #CBD5E1;
}
.cart-status-icon{
    width:72px;height:72px;border-radius:50%;margin:0 auto 16px;
    display:flex;align-items:center;justify-content:center;font-size:32px;
}
.cart-status-card.enabled .cart-status-icon{background:var(--success);color:white;}
.cart-status-card.disabled .cart-status-icon{background:#94A3B8;color:white;}
.cart-status-card h3{font-size:18px;font-weight:900;margin-bottom:6px;}
.cart-status-card.enabled h3{color:var(--success);}
.cart-status-card.disabled h3{color:var(--text-3);}
.cart-status-card p{font-size:13px;}
.cart-status-card.enabled p{color:#065F46;}
.cart-status-card.disabled p{color:var(--text-3);}

/* ─── ميزات السلة ─── */
.cart-features{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:24px;}
@media(max-width:500px){.cart-features{grid-template-columns:1fr;}}
.feature-item{
    background:var(--surface-2);border:1.5px solid var(--border);
    border-radius:var(--radius-sm);padding:14px 16px;
    display:flex;align-items:flex-start;gap:10px;
}
.feature-icon{
    width:34px;height:34px;border-radius:var(--radius-sm);
    background:linear-gradient(135deg,var(--primary),var(--primary-l));
    color:white;display:flex;align-items:center;justify-content:center;
    font-size:16px;flex-shrink:0;
}
.feature-text h5{font-size:13px;font-weight:800;color:var(--text);margin-bottom:3px;}
.feature-text p{font-size:11px;color:var(--text-3);line-height:1.5;}

/* ─── تحذير ─── */
.cart-warning{
    background:var(--warning-l);border:1.5px solid #FDE68A;
    border-radius:var(--radius-sm);padding:14px 16px;
    display:flex;gap:10px;align-items:flex-start;margin-bottom:20px;
}
.cart-warning h4{font-size:13px;font-weight:800;color:var(--warning);margin-bottom:4px;}
.cart-warning p{font-size:12px;color:#92400E;line-height:1.6;}

.pwd-bar{height:4px;border-radius:4px;margin-top:6px;transition:var(--tr);background:var(--border)}
.pwd-bar.weak  {background:var(--danger);width:33%}
.pwd-bar.medium{background:var(--warning);width:66%}
.pwd-bar.strong{background:var(--success);width:100%}
.pwd-label{font-size:11px;margin-top:4px;font-weight:700}
.pwd-bar.weak+.pwd-label  {color:var(--danger)}
.pwd-bar.medium+.pwd-label{color:var(--warning)}
.pwd-bar.strong+.pwd-label{color:var(--success)}

.admin-table-wrap{border-radius:var(--radius-sm);border:1px solid var(--border);overflow:hidden;margin-top:16px}
table{width:100%;border-collapse:collapse;font-size:13px}
th{background:linear-gradient(135deg,var(--primary),var(--primary-d));color:white;padding:12px 14px;text-align:right;font-weight:700;font-size:12px}
td{padding:12px 14px;border-bottom:1px solid #F1F5F9;color:var(--text-2);vertical-align:middle}
tr:last-child td{border-bottom:none}
tr:hover td{background:#F8FAFC}
.admin-av{width:34px;height:34px;border-radius:50%;background:linear-gradient(135deg,var(--primary),var(--primary-l));color:white;display:flex;align-items:center;justify-content:center;font-weight:900;font-size:14px;text-transform:uppercase}
.badge-you    {background:var(--success-l);color:var(--success);padding:3px 8px;border-radius:20px;font-size:11px;font-weight:700;border:1px solid #A7F3D0}
.badge-valid  {background:var(--success-l);color:var(--success);padding:3px 10px;border-radius:20px;font-size:11px;font-weight:700;border:1px solid #A7F3D0}
.badge-invalid{background:var(--danger-l);color:var(--danger);padding:3px 10px;border-radius:20px;font-size:11px;font-weight:700;border:1px solid #FECACA}
.invalid-row td{background:#FFF8F8!important}

.warn-box{background:linear-gradient(135deg,#FFF5F5,#FEF2F2);border:1.5px solid #FECACA;border-radius:var(--radius-sm);padding:14px 16px;margin-bottom:16px;display:flex;gap:10px;align-items:flex-start}
.warn-box h4{font-size:13px;font-weight:800;color:var(--danger);margin-bottom:4px}
.warn-box p{font-size:12px;color:#991B1B;line-height:1.6}

.add-box{background:var(--surface-2);border:1.5px solid var(--border);border-radius:var(--radius-sm);padding:20px;margin-bottom:20px}
.add-box h4{font-size:14px;font-weight:800;color:var(--text);margin-bottom:16px;display:flex;align-items:center;gap:8px}

.btn{padding:10px 20px;border-radius:var(--radius-sm);font-weight:700;cursor:pointer;transition:var(--tr);display:inline-flex;align-items:center;gap:7px;font-size:13px;border:none;text-decoration: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,.3)}
.btn-success      {background:var(--success);color:white}
.btn-success:hover{background:#047857;transform:translateY(-1px);box-shadow:0 4px 14px rgba(5,150,105,.3)}
.btn-danger       {background:var(--danger);color:white}
.btn-danger:hover {background:#B91C1C;transform:translateY(-1px);box-shadow:0 4px 14px rgba(220,38,38,.3)}
.btn-warning      {background:var(--warning);color:white}
.btn-warning:hover{background:#B45309;transform:translateY(-1px)}
.btn-lg{padding:15px 32px;font-size:15px;border-radius:var(--radius);}
.btn-sm{padding:6px 12px;font-size:12px}
.btn-ghost{background:transparent;color:var(--danger);border:1.5px solid #FECACA}
.btn-ghost:hover{background:var(--danger-l)}
.form-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:24px;padding-top:18px;border-top:1.5px solid var(--border)}
::-webkit-scrollbar{width:5px;height:5px}
::-webkit-scrollbar-thumb{background:var(--primary-l);border-radius:10px}
@media(max-width:768px){
    body{padding:12px}
    .header{flex-direction:column;gap:12px}
    .tab-pane{padding:18px}
    .logo-area{flex-direction:column;align-items:flex-start}
    .form-actions{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:white;border:none;padding:10px 13px;border-radius:var(--radius-sm);cursor:pointer;display:flex;align-items:center">
    <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="icon-wrap">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>
        </span>
        إعدادات الموقع
    </h1>
    <span style="font-size:12px;color:var(--text-3);font-weight:600">👤 <?= htmlspecialchars($settings['email']) ?></span>
</div>

<?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'])): ?>
    <div class="msg msg-error">❌ <?= htmlspecialchars($_SESSION['error']) ?></div>
    <?php unset($_SESSION['error']); ?>
<?php endif; ?>

<div class="tabs-wrapper">
    <div class="tabs-nav">
        <?php
        $tabs = [
            ['id'=>'general',  'label'=>'الإعدادات العامة', 'icon'=>'<path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>'],
            ['id'=>'pixel',    'label'=>'Meta Pixel',        'icon'=>'<rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/>'],
            ['id'=>'social',   'label'=>'التواصل الاجتماعي','icon'=>'<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>'],
            ['id'=>'cart',     'label'=>'سلة التسوق',        'icon'=>'<circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 002 1.61h9.72a2 2 0 002-1.61L23 6H6"/>'],
            ['id'=>'password', 'label'=>'كلمة المرور',       'icon'=>'<rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/>'],
            ['id'=>'admins',   'label'=>'الأدمين',           'icon'=>'<path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 00-3-3.87"/><path d="M16 3.13a4 4 0 010 7.75"/>'],
        ];
        foreach ($tabs as $t):
        ?>
        <button class="tab-btn <?= $active_tab==$t['id']?'active':'' ?>" onclick="openTab('<?= $t['id'] ?>',this)">
            <span class="ti"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><?= $t['icon'] ?></svg></span>
            <?= $t['label'] ?>
        </button>
        <?php endforeach; ?>
    </div>

    <!-- ══════ الإعدادات العامة ══════ -->
    <div id="general" class="tab-pane <?= $active_tab=='general'?'active':'' ?>">
        <div class="section-title">
            <span class="st-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></svg></span>
            معلومات المتجر
        </div>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="update_settings" value="1">
            <div class="logo-area">
                <div class="logo-box" id="logoBox">
                    <?php if (!empty($store_settings['logo'])): ?>
                        <img src="<?= htmlspecialchars($store_settings['logo']) ?>" alt="شعار">
                    <?php else: ?>
                        <span class="no-logo">🏪</span>
                    <?php endif; ?>
                </div>
                <div class="logo-info">
                    <h4>شعار المتجر</h4>
                    <p>JPG، PNG، SVG — 200×200 على الأقل</p>
                    <label class="btn-choose" for="logoFile">
                        <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="16 16 12 12 8 16"/><line x1="12" y1="12" x2="12" y2="21"/><path d="M20.39 18.39A5 5 0 0018 9h-1.26A8 8 0 103 16.3"/></svg>
                        اختر صورة
                    </label>
                    <input type="file" name="logo" id="logoFile" accept="image/*" class="logo-file" onchange="prevLogo(this)">
                </div>
            </div>
            <div class="form-row-2">
                <div class="form-group">
                    <label>اسم المتجر <span class="req">*</span></label>
                    <input type="text" name="name" required value="<?= htmlspecialchars($store_settings['name']??'') ?>" placeholder="متجر ميديشوب">
                </div>
                <div class="form-group">
                    <label>رقم الهاتف <span class="req">*</span></label>
                    <input type="tel" name="phone" required value="<?= htmlspecialchars($store_settings['phone']??'') ?>" placeholder="0550000000">
                </div>
            </div>
            <div class="form-group">
                <label>وصف المتجر <span class="opt">(اختياري)</span></label>
                <textarea name="description" placeholder="وصف مختصر..."><?= htmlspecialchars($store_settings['description']??'') ?></textarea>
            </div>
            <div class="form-row-2">
                <div class="form-group">
                    <label>البريد الإلكتروني (للدخول) <span class="req">*</span></label>
                    <input type="email" name="email" id="loginEmail" required
                           value="<?= htmlspecialchars($settings['email']??'') ?>"
                           oninput="checkEmail(this,'loginEmailNote')"
                           onblur="checkEmail(this,'loginEmailNote',true)">
                    <span class="field-note hint" id="loginEmailNote">يُستخدم لتسجيل الدخول</span>
                </div>
                <div class="form-group">
                    <label>بريد التواصل مع العملاء <span class="opt">(اختياري)</span></label>
                    <input type="email" name="emailp"
                           value="<?= htmlspecialchars($store_settings['emailp']??'') ?>"
                           placeholder="support@example.com"
                           oninput="checkEmail(this,'emailpNote',false,true)"
                           onblur="checkEmail(this,'emailpNote',true,true)">
                    <span class="field-note hint" id="emailpNote"></span>
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <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"/><polyline points="7 3 7 8 15 8"/></svg>
                    حفظ الإعدادات
                </button>
            </div>
        </form>
    </div>

    <!-- ══════ Meta Pixel ══════ -->
    <div id="pixel" class="tab-pane <?= $active_tab=='pixel'?'active':'' ?>">
        <div class="section-title">
            <span class="st-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg></span>
            إعدادات Meta Pixel
        </div>
        <div class="pixel-info">
            <h4><svg width="16" height="16" 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> ما هو Meta Pixel؟</h4>
            <p>كود تتبع يساعدك على قياس فعالية إعلاناتك على فيسبوك وإنستجرام. احصل على المعرف من <a href="https://business.facebook.com/events_manager" target="_blank">Events Manager ↗</a></p>
        </div>
        <form method="POST">
            <input type="hidden" name="update_settings" value="1">
            <div class="toggle-row">
                <div class="toggle-info">
                    <h4>تفعيل Meta Pixel</h4>
                    <p>سيُضمَّن كود البيكسل في صفحات المتجر عند التفعيل</p>
                </div>
                <label class="switch">
                    <input type="checkbox" name="meta_pixel_enabled" id="pixelToggle" <?= $store_settings['meta_pixel_enabled']?'checked':'' ?>>
                    <span class="slider"></span>
                </label>
            </div>
            <div class="form-group" id="pixelGroup" style="<?= $store_settings['meta_pixel_enabled']?'':'opacity:.5' ?>">
                <label>معرف البيكسل (Pixel ID) <span class="req">*</span></label>
                <input type="text" name="meta_pixel_id" id="pixelId" value="<?= htmlspecialchars($store_settings['meta_pixel_id']??'') ?>" placeholder="1234567890123456" maxlength="20">
                <span class="field-note hint">أرقام فقط — عادةً 15-16 رقماً</span>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">حفظ إعدادات Pixel</button>
            </div>
        </form>
    </div>

    <!-- ══════ التواصل الاجتماعي ══════ -->
    <div id="social" class="tab-pane <?= $active_tab=='social'?'active':'' ?>">
        <div class="section-title">
            <span class="st-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg></span>
            روابط التواصل الاجتماعي
        </div>
        <form method="POST">
            <input type="hidden" name="update_settings" value="1">
            <div class="form-group">
                <label><span style="background:#1877F2;color:white;border-radius:4px;padding:2px 6px;font-size:11px;margin-left:6px">f</span> فيسبوك <span class="opt">(اختياري)</span></label>
                <input type="url" name="facebook" value="<?= htmlspecialchars($store_settings['facebook']??'') ?>" placeholder="https://facebook.com/yourpage">
            </div>
            <div class="form-group">
                <label><span style="background:#229ED9;color:white;border-radius:4px;padding:2px 6px;font-size:11px;margin-left:6px">✈</span> تيليغرام <span class="opt">(اختياري)</span></label>
                <input type="url" name="telegram" value="<?= htmlspecialchars($store_settings['telegram']??'') ?>" placeholder="https://t.me/yourchannel">
            </div>
            <div class="form-group">
                <label><span style="background:linear-gradient(45deg,#f09433,#e6683c,#dc2743,#cc2366,#bc1888);color:white;border-radius:4px;padding:2px 6px;font-size:11px;margin-left:6px">◎</span> إنستجرام <span class="opt">(اختياري)</span></label>
                <input type="url" name="instagram" value="<?= htmlspecialchars($store_settings['instgrame']??'') ?>" placeholder="https://instagram.com/yourprofile">
            </div>
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">حفظ الروابط</button>
            </div>
        </form>
    </div>

    <!-- ══════ سلة التسوق ══════ -->
    <div id="cart" class="tab-pane <?= $active_tab=='cart'?'active':'' ?>">
        <div class="section-title">
            <span class="st-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 002 1.61h9.72a2 2 0 002-1.61L23 6H6"/></svg></span>
            إعدادات سلة التسوق
        </div>

        <!-- بطاقة الحالة الحالية -->
        <?php $cart_on = !empty($store_settings['cart_enabled']); ?>
        <div class="cart-status-card <?= $cart_on ? 'enabled' : 'disabled' ?>" id="cartStatusCard">
            <div class="cart-status-icon">
                <?php if($cart_on): ?>
                    <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 01-8 0"/></svg>
                <?php else: ?>
                    <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 002 1.61h9.72a2 2 0 002-1.61L23 6H6"/></svg>
                <?php endif; ?>
            </div>
            <h3><?= $cart_on ? '✅ السلة مفعّلة' : '⛔ السلة معطّلة' ?></h3>
            <p><?= $cart_on
                ? 'العملاء يستطيعون الآن إضافة منتجات متعددة قبل تأكيد الطلب'
                : 'السلة مخفية حالياً — كل العملاء يطلبون منتجاً واحداً في كل مرة' ?>
            </p>
        </div>

        <!-- ميزات السلة -->
        <div class="cart-features">
            <div class="feature-item">
                <div class="feature-icon">🛒</div>
                <div class="feature-text">
                    <h5>طلبات متعددة دفعة واحدة</h5>
                    <p>يضيف العميل عدة منتجات ثم يطلبها معاً بتفاصيل توصيل واحدة</p>
                </div>
            </div>
            <div class="feature-item">
                <div class="feature-icon">💾</div>
                <div class="feature-text">
                    <h5>حفظ تلقائي في المتصفح</h5>
                    <p>تُحفظ السلة محلياً — لا تضيع عند إغلاق الصفحة</p>
                </div>
            </div>
            <div class="feature-item">
                <div class="feature-icon">📦</div>
                <div class="feature-text">
                    <h5>ملخّص الطلب قبل التأكيد</h5>
                    <p>يرى العميل إجمالي المنتجات والتوصيل قبل إرسال الطلب</p>
                </div>
            </div>
            <div class="feature-item">
                <div class="feature-icon">🔌</div>
                <div class="feature-text">
                    <h5>لا يؤثر على طريقة الطلب المعتادة</h5>
                    <p>زر "اطلب الآن" يبقى كما هو — السلة خيار إضافي للعميل</p>
                </div>
            </div>
        </div>

        <?php if(!$cart_on): ?>
        <!-- تحذير عند التفعيل -->
        <div class="cart-warning">
            <span style="font-size:20px;flex-shrink:0">⚠️</span>
            <div>
                <h4>قبل التفعيل — تأكد من رفع الملفات</h4>
                <p>يجب أن تكون الملفات التالية موجودة في جذر الموقع قبل التفعيل:<br>
                <strong>cart.php</strong> — <strong>cart.js</strong> — <strong>get_delivery_price.php</strong> — <strong>submit_order_cart.php</strong></p>
            </div>
        </div>
        <?php endif; ?>

        <!-- زر التفعيل/التعطيل -->
        <form method="POST" onsubmit="return confirmCartToggle(<?= $cart_on ? 'true' : 'false' ?>)">
            <input type="hidden" name="update_cart" value="1">
            <?php if(!$cart_on): ?>
                <input type="hidden" name="cart_enabled" value="1">
                <button type="submit" class="btn btn-success btn-lg" style="width:100%;justify-content:center;">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>
                    تفعيل سلة التسوق
                </button>
            <?php else: ?>
                <button type="submit" class="btn btn-danger btn-lg" style="width:100%;justify-content:center;">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                    تعطيل سلة التسوق
                </button>
            <?php endif; ?>
        </form>

        <!-- رابط السلة -->
        <?php if($cart_on): ?>
        <div style="margin-top:16px;background:#F0FDF4;border:1.5px solid #A7F3D0;border-radius:var(--radius-sm);padding:14px 18px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;">
            <div>
                <div style="font-size:12px;font-weight:700;color:var(--success);margin-bottom:4px">🔗 رابط صفحة السلة</div>
                <code style="font-size:13px;color:var(--text-2)">cart.php</code>
            </div>
            <a href="<?= BASE_URL ?>cart.php" target="_blank" class="btn btn-success btn-sm">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
                معاينة السلة
            </a>
        </div>
        <?php endif; ?>
    </div>

    <!-- ══════ كلمة المرور ══════ -->
    <div id="password" class="tab-pane <?= $active_tab=='password'?'active':'' ?>">
        <div class="section-title">
            <span class="st-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg></span>
            تغيير كلمة المرور
        </div>
        <form method="POST">
            <input type="hidden" name="change_password" value="1">
            <?php foreach ([['currentPwd','current_password','كلمة المرور الحالية'],['newPwd','new_password','كلمة المرور الجديدة'],['confirmPwd','confirm_password','تأكيد كلمة المرور الجديدة']] as $f): ?>
            <div class="form-group">
                <label><?= $f[2] ?> <span class="req">*</span></label>
                <div style="position:relative">
                    <input type="password" name="<?= $f[1] ?>" id="<?= $f[0] ?>" required placeholder="••••••••"
                    <?= $f[0]=='newPwd'?'oninput="pwdStrength(this)"':'' ?>
                    <?= $f[0]=='confirmPwd'?'oninput="pwdMatch()"':'' ?>>
                    <button type="button" onclick="togPwd('<?= $f[0] ?>',this)" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--text-3);display:flex;align-items:center">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                    </button>
                </div>
                <?php if ($f[0]=='newPwd'): ?>
                    <div class="pwd-bar" id="pwdBar"></div>
                    <div class="pwd-label" id="pwdLabel"></div>
                <?php elseif ($f[0]=='confirmPwd'): ?>
                    <div id="matchMsg" style="font-size:11px;margin-top:5px;font-weight:700"></div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
            <div class="form-actions">
                <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="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 11-7.778 7.778 5.5 5.5 0 017.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/></svg>
                    تغيير كلمة المرور
                </button>
            </div>
        </form>
    </div>

    <!-- ══════ الأدمين ══════ -->
    <div id="admins" class="tab-pane <?= $active_tab=='admins'?'active':'' ?>">
        <div class="section-title">
            <span class="st-icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/></svg></span>
            إدارة المسؤولين
        </div>

        <?php
        $invalidAdmins = array_filter($admins, fn($a) => !isValidEmail($a['email']));
        if ($invalidAdmins): ?>
        <div class="warn-box">
            <span style="font-size:20px;flex-shrink:0">⚠️</span>
            <div>
                <h4>حسابات ببريد إلكتروني غير صالح</h4>
                <p>الحسابات المميزة باللون الأحمر تحتوي بريداً غير صحيح. يُنصح بحذفها لمنع مشاكل تسجيل الدخول.</p>
            </div>
        </div>
        <?php endif; ?>

        <div class="add-box">
            <h4>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#0284C7" stroke-width="2.5"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
                دعوة مسؤول جديد عبر الإيميل
            </h4>
            <form method="POST" onsubmit="return validateInvite()">
                <input type="hidden" name="invite_admin" value="1">
                <div style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap">
                    <div class="form-group" style="margin-bottom:0;flex:1;min-width:220px">
                        <label>البريد الإلكتروني <span class="req">*</span></label>
                        <input type="email" name="invite_email" id="inviteEmail" required
                               placeholder="admin@example.com"
                               oninput="checkInviteEmail()" onblur="checkInviteEmail(true)">
                        <span class="field-note hint" id="inviteEmailNote"></span>
                    </div>
                    <div style="padding-bottom:2px">
                        <button type="submit" class="btn btn-primary btn-sm">
                            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
                            إرسال دعوة
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <?php if (!empty($pending_invites)): ?>
        <div style="background:#EFF6FF;border:1.5px solid #BFDBFE;border-radius:var(--radius-sm);padding:16px;margin-bottom:20px">
            <h4 style="font-size:13px;font-weight:800;color:var(--primary);margin-bottom:12px;display:flex;align-items:center;gap:8px">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                دعوات معلقة (<?= count($pending_invites) ?>)
            </h4>
            <?php foreach ($pending_invites as $inv): ?>
            <div style="display:flex;align-items:center;justify-content:space-between;background:white;border-radius:var(--radius-sm);padding:10px 14px;margin-bottom:8px;border:1px solid #BFDBFE;flex-wrap:wrap;gap:8px">
                <div>
                    <strong style="font-size:13px;color:var(--text)"><?= htmlspecialchars($inv['email']) ?></strong>
                    <span style="font-size:11px;color:var(--text-3);margin-right:10px">تنتهي: <?= date('d/m/Y H:i', strtotime($inv['expiry'])) ?></span>
                </div>
                <form method="POST" onsubmit="return confirm('إلغاء هذه الدعوة؟')">
                    <input type="hidden" name="cancel_invite" value="1">
                    <input type="hidden" name="invite_id" value="<?= $inv['id'] ?>">
                    <button type="submit" class="btn btn-ghost btn-sm">
                        <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>
                        إلغاء
                    </button>
                </form>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <div class="admin-table-wrap">
            <table>
                <thead>
                    <tr>
                        <th width="45">#</th>
                        <th>الأفاتار</th>
                        <th>البريد الإلكتروني</th>
                        <th>الحالة</th>
                        <th width="110">الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($admins as $a):
                    $valid = isValidEmail($a['email']);
                    $isMe  = ($a['id'] == $_SESSION['user']['id']);
                ?>
                <tr class="<?= !$valid?'invalid-row':'' ?>">
                    <td><strong><?= $a['id'] ?></strong></td>
                    <td>
                        <div style="display:flex;align-items:center;gap:10px">
                            <div class="admin-av"><?= mb_strtoupper(mb_substr($a['email'],0,1)) ?></div>
                            <?php if ($isMe): ?><span class="badge-you">أنت</span><?php endif; ?>
                        </div>
                    </td>
                    <td>
                        <strong style="color:var(--text)"><?= htmlspecialchars($a['email']) ?></strong>
                        <?php if (!$valid): ?><br><small style="color:var(--danger);font-size:11px">⚠️ بريد غير صالح</small><?php endif; ?>
                    </td>
                    <td>
                        <?php if ($valid): ?><span class="badge-valid">✅ صالح</span>
                        <?php else: ?><span class="badge-invalid">❌ غير صالح</span><?php endif; ?>
                    </td>
                    <td>
                        <?php if (!$isMe): ?>
                        <form method="POST" onsubmit="return confirm('حذف هذا المسؤول نهائياً؟')">
                            <input type="hidden" name="delete_admin" value="1">
                            <input type="hidden" name="admin_id" value="<?= $a['id'] ?>">
                            <button type="submit" class="btn btn-ghost btn-sm">
                                <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"/></svg>
                                حذف
                            </button>
                        </form>
                        <?php else: ?><span style="color:var(--text-3);font-size:12px">—</span><?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

</div><!-- /tabs-wrapper -->
</div><!-- /container -->

<script>
function openTab(id,btn){
    document.querySelectorAll('.tab-pane').forEach(p=>p.classList.remove('active'));
    document.querySelectorAll('.tab-btn').forEach(b=>b.classList.remove('active'));
    document.getElementById(id).classList.add('active');
    btn.classList.add('active');
    history.replaceState(null,'','?tab='+id);
}
function prevLogo(input){
    if(!input.files||!input.files[0])return;
    const r=new FileReader();
    r.onload=e=>{document.getElementById('logoBox').innerHTML='<img src="'+e.target.result+'" alt="شعار">';};
    r.readAsDataURL(input.files[0]);
}
function togPwd(id,btn){
    const inp=document.getElementById(id),show=inp.type==='password';
    inp.type=show?'text':'password';
    btn.innerHTML=show
        ?'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>'
        :'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
}
function isEmailValid(email){
    if(!email)return false;
    const re=/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
    if(!re.test(email))return false;
    const domain=email.split('@')[1];
    if(!domain||!domain.includes('.'))return false;
    const tld=domain.split('.').pop();
    if(tld.length<2)return false;
    if(/^[.\-]|[.\-]$/.test(domain))return false;
    return true;
}
function checkEmail(inp,noteId,onBlur=false,optional=false){
    const val=inp.value.trim();
    const note=document.getElementById(noteId);
    if(!val){
        if(!optional){inp.classList.remove('ok','err');note.textContent=onBlur?'البريد مطلوب':'يُستخدم لتسجيل الدخول';note.className='field-note '+(onBlur?'err':'hint');}
        else{inp.classList.remove('ok','err');note.textContent='';note.className='field-note hint';}
        return !(!optional&&onBlur);
    }
    if(!isEmailValid(val)){
        if(onBlur||val.length>5){inp.classList.add('err');inp.classList.remove('ok');note.textContent='❌ غير صالح — مثال: name@domain.com';note.className='field-note err';}
        return false;
    }
    inp.classList.add('ok');inp.classList.remove('err');note.textContent='✅ صالح';note.className='field-note ok';
    return true;
}
function checkInviteEmail(onBlur=false){
    const inp=document.getElementById('inviteEmail'),note=document.getElementById('inviteEmailNote'),val=inp.value.trim();
    if(!val){inp.classList.remove('ok','err');note.textContent='';note.className='field-note hint';return false;}
    if(!isEmailValid(val)){if(onBlur||val.length>5){inp.classList.add('err');inp.classList.remove('ok');note.textContent='❌ غير صالح — name@domain.com';note.className='field-note err';}return false;}
    inp.classList.add('ok');inp.classList.remove('err');note.textContent='✅ صالح';note.className='field-note ok';
    return true;
}
function validateInvite(){
    if(!checkInviteEmail(true)){alert('أدخل بريداً إلكترونياً صحيحاً — مثال: admin@gmail.com');return false;}
    return true;
}
function pwdStrength(inp){
    const val=inp.value,bar=document.getElementById('pwdBar'),lbl=document.getElementById('pwdLabel');
    if(!val){bar.className='pwd-bar';lbl.textContent='';return;}
    let s=0;
    if(val.length>=8)s++;if(/[A-Z]/.test(val))s++;if(/[0-9]/.test(val))s++;if(/[^A-Za-z0-9]/.test(val))s++;
    if(s<=1){bar.className='pwd-bar weak';lbl.textContent='ضعيفة';}
    else if(s<=3){bar.className='pwd-bar medium';lbl.textContent='متوسطة';}
    else{bar.className='pwd-bar strong';lbl.textContent='قوية ✓';}
}
function pwdMatch(){
    const p1=document.getElementById('newPwd').value,p2=document.getElementById('confirmPwd').value;
    const msg=document.getElementById('matchMsg');
    if(!p2){msg.textContent='';return;}
    msg.style.color=p1===p2?'var(--success)':'var(--danger)';
    msg.textContent=p1===p2?'✓ متطابقتان':'✗ غير متطابقتين';
}
function confirmCartToggle(isEnabled){
    if(isEnabled){
        return confirm('هل تريد تعطيل سلة التسوق؟\nلن يتمكن العملاء من استخدام السلة بعد ذلك.');
    } else {
        return confirm('هل تريد تفعيل سلة التسوق؟\nتأكد أولاً من رفع ملفات: cart.php و cart.js و get_delivery_price.php و submit_order_cart.php');
    }
}
document.addEventListener('DOMContentLoaded',()=>{
    const tog=document.getElementById('pixelToggle');
    const grp=document.getElementById('pixelGroup');
    const pid=document.getElementById('pixelId');
    if(tog){
        tog.addEventListener('change',()=>{grp.style.opacity=tog.checked?'1':'.5';pid.disabled=!tog.checked;});
        pid.disabled=!tog.checked;
    }
});
</script>
</body>
</html>