<?php
require_once "../includes/auth.php";
require_once "../config/db.php";

// جلب التصنيفات والمدن من الجداول الأخرى
$categories = $pdo->query("SELECT id, name FROM categories ORDER BY name ASC")->fetchAll();
$cities = $pdo->query("SELECT id, name FROM cities ORDER BY name ASC")->fetchAll();

$company_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$company = $pdo->prepare("SELECT * FROM companies WHERE id=?");
$company->execute([$company_id]);
$company = $company->fetch(PDO::FETCH_ASSOC);

// حماية: التأكد من وجود بيانات الشركة قبل عرض أو معالجة أي شيء
if (!$company || !is_array($company)) {
    die('<div style="color:red;text-align:center;padding:40px;">الشركة غير موجودة</div>');
}

$error = '';
$success = '';

// --- معالجة حذف صورة إضافية (عبر GET) ---
if (isset($_GET['delete_image'])) {
    $img_to_delete = $_GET['delete_image'];
    $images_arr = [];
    if (!empty($company['images'])) $images_arr = json_decode($company['images'], true) ?: [];
    $new_images = [];
    foreach ($images_arr as $img) {
        if ($img !== $img_to_delete) {
            $new_images[] = $img;
        } else {
            $img_path = dirname(__DIR__) . '/' . $img;
            if (file_exists($img_path)) unlink($img_path);
        }
    }
    $company['images'] = json_encode($new_images, JSON_UNESCAPED_UNICODE);
    $stmt = $pdo->prepare("UPDATE companies SET images=? WHERE id=?");
    $stmt->execute([$company['images'], $company_id]);
    // إعادة جلب الشركة بعد الحذف
    header("Location: company_edit.php?id=$company_id&msg=img_deleted");
    exit;
}

// --- معالجة التعديل ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $category_id = intval($_POST['category_id'] ?? 0);
    $city_id = intval($_POST['city_id'] ?? 0);
    $about = trim($_POST['about'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $whatsapp = trim($_POST['whatsapp'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $website = trim($_POST['website'] ?? '');
    $map_link = trim($_POST['map_link'] ?? '');
    $status = $_POST['status'] ?? 'pending';

    // رفع الشعار الجديد إذا تم اختياره
    $logo = $company['logo'];
    if (!empty($_FILES['logo']['name'])) {
        $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $logo_name = 'logo_' . $company_id . '_' . time() . '.' . $ext;
        $logo_path = '../uploads/companies/' . $logo_name;
        if (move_uploaded_file($_FILES['logo']['tmp_name'], $logo_path)) {
            $logo = 'uploads/companies/' . $logo_name;
        } else {
            $error = "فشل رفع الشعار.";
        }
    }

    // رفع صورة الغلاف الجديدة إذا تم اختيارها
    $cover = $company['cover'];
    if (!empty($_FILES['cover']['name'])) {
        $ext = pathinfo($_FILES['cover']['name'], PATHINFO_EXTENSION);
        $cover_name = 'cover_' . $company_id . '_' . time() . '.' . $ext;
        $cover_path = '../uploads/companies/' . $cover_name;
        if (move_uploaded_file($_FILES['cover']['tmp_name'], $cover_path)) {
            $cover = 'uploads/companies/' . $cover_name;
        } else {
            $error = "فشل رفع صورة الغلاف.";
        }
    }

    // رفع صور إضافية متعددة
    $images = $company['images'];
    if (!empty($_FILES['images']['name'][0])) {
        $uploaded = [];
        foreach ($_FILES['images']['name'] as $k => $img) {
            if ($_FILES['images']['error'][$k] === UPLOAD_ERR_OK && $img) {
                $ext = pathinfo($img, PATHINFO_EXTENSION);
                $img_name = 'img_' . $company_id . '_' . time() . "_$k." . $ext;
                $img_path = '../uploads/companies/' . $img_name;
                if (move_uploaded_file($_FILES['images']['tmp_name'][$k], $img_path)) {
                    $uploaded[] = 'uploads/companies/' . $img_name;
                }
            }
        }
        if ($uploaded) {
            $old_images = [];
            if ($images) $old_images = json_decode($images, true) ?: [];
            $images = json_encode(array_merge($old_images, $uploaded), JSON_UNESCAPED_UNICODE);
        }
    }

    if (!$error && $name) {
        $stmt = $pdo->prepare("UPDATE companies SET name=?, category_id=?, city_id=?, about=?, phone=?, whatsapp=?, email=?, website=?, map_link=?, logo=?, cover=?, images=?, status=? WHERE id=?");
        $stmt->execute([
            $name, $category_id, $city_id, $about, $phone, $whatsapp, $email, $website, $map_link,
            $logo, $cover, $images, $status, $company_id
        ]);
        $success = "تم تعديل بيانات الشركة بنجاح!";
        // جلب البيانات بعد التعديل
        $company = $pdo->prepare("SELECT * FROM companies WHERE id=?");
        $company->execute([$company_id]);
        $company = $company->fetch(PDO::FETCH_ASSOC);
    } elseif (!$error) {
        $error = "جميع الحقول مطلوبة!";
    }
}

// معالجة الصور الإضافية للعرض
$image_list = [];
if (!empty($company['images'])) {
    $decoded = json_decode($company['images'], true);
    if (is_array($decoded)) $image_list = $decoded;
}
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>تعديل بيانات الشركة</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        body {
            background: #f8f9fa;
            font-family: 'Cairo', sans-serif;
            color: #2e2340;
            margin: 0;
        }
        .container {
            max-width: 700px;
            margin: 45px auto 0 auto;
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 7px 30px #e6e6e6;
            padding: 38px 24px 25px 24px;
            min-height: 320px;
        }
        .top-bar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 25px;
        }
        h2 {
            color: #3e165a;
            font-size: 1.4rem;
            font-weight: 800;
            margin: 0;
            display: flex;
            align-items: center;
        }
        h2 i { margin-left: 8px; color: #7c3aed;}
        .back-btn {
            background: linear-gradient(135deg, #3e165a 60%, #7c3aed 100%);
            color: #fff !important;
            padding: 8px 22px 8px 15px;
            border-radius: 50px;
            border: none;
            font-size: 1rem;
            font-weight: 700;
            cursor: pointer;
            display: flex;
            align-items: center;
            text-decoration: none;
            transition: background 0.2s;
            box-shadow: 0 3px 15px rgba(62,22,90,0.09);
        }
        .back-btn i { margin-left: 9px; font-size: 1.2em;}
        .back-btn:hover { background: linear-gradient(135deg, #7c3aed, #3e165a); }
        label { font-weight:600; margin-top: 18px; display: block; color: #481c79;}
        input[type=text], input[type=email], input[type=url], select, textarea {
            width: 100%;
            padding: 8px 11px;
            margin-top: 7px;
            border-radius: 8px;
            border: 1px solid #e3d7fc;
            background: #f8f6fc;
            font-size: 1rem;
            font-family: inherit;
            transition: border 0.18s;
        }
        input[type=text]:focus, input[type=email]:focus, input[type=url]:focus, select:focus, textarea:focus {
            border-color: #7c3aed;
            outline: none;
        }
        textarea { min-height: 70px; }
        .img-row { display:flex; gap:10px; margin-bottom:7px; margin-top:8px;}
        .img-box { display:flex; flex-direction:column; align-items:center; }
        .img-thumb {
            width: 60px; height: 42px; border-radius: 7px; object-fit:cover;
            background:#fafafd; box-shadow: 0 1px 7px #eaeaea;
            border: 1px solid #eee;
        }
        .img-delete-btn {
            background: #e74c3c;
            color: #fff;
            border: none;
            padding: 2px 9px 1px 9px;
            border-radius: 5px;
            font-size: 13px;
            margin-top: 3px;
            cursor: pointer;
            transition: background 0.15s;
        }
        .img-delete-btn:hover { background: #c0392b; }
        .form-actions { margin-top: 26px; text-align:center; }
        .btn-main {
            background: #7c3aed;
            color: #fff;
            border: none;
            font-weight: 700;
            border-radius: 50px;
            padding: 11px 38px;
            font-size: 1.09rem;
            cursor: pointer;
            transition: background 0.17s;
        }
        .btn-main i { margin-left: 6px;}
        .btn-main:hover { background: #3e165a; }
        .alert-error {
            color: #c00;
            background: #fde4e4;
            padding: 8px 18px;
            border-radius: 7px;
            margin-bottom: 17px;
            text-align: right;
            font-weight: bold;
        }
        .alert-success {
            color: #128a24;
            background: #e8faee;
            padding: 8px 18px;
            border-radius: 7px;
            margin-bottom: 17px;
            text-align: right;
            font-weight: bold;
        }
        @media (max-width:600px){
            .container { padding: 11px 2vw; }
            .btn-main, .back-btn { padding:7px 12vw; font-size:15px;}
            .img-thumb { width:38px; height: 24px;}
            h2 { font-size: 1.05rem;}
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="top-bar">
            <h2><i class="fa fa-edit"></i> تعديل بيانات الشركة</h2>
            <a href="companies.php" class="back-btn"><i class="fa fa-arrow-right"></i> العودة للقائمة</a>
        </div>
        <?php if ($error): ?><div class="alert-error"><?= $error ?></div><?php endif; ?>
        <?php if ($success): ?><div class="alert-success"><?= $success ?></div><?php endif; ?>
        <?php if (isset($_GET['msg']) && $_GET['msg']=='img_deleted'): ?>
            <div class="alert-success">تم حذف الصورة بنجاح!</div>
        <?php endif; ?>

        <form method="post" enctype="multipart/form-data">
            <label>اسم الشركة *</label>
            <input type="text" name="name" required value="<?= htmlspecialchars($company['name'] ?? '') ?>">

            <label>التصنيف</label>
            <select name="category_id">
                <option value="">اختر التصنيف</option>
                <?php foreach ($categories as $cat): ?>
                <option value="<?= $cat['id'] ?>" <?= ($company['category_id']==$cat['id'])?'selected':'' ?>>
                    <?= htmlspecialchars($cat['name']) ?>
                </option>
                <?php endforeach; ?>
            </select>

            <label>المدينة</label>
            <select name="city_id">
                <option value="">اختر المدينة</option>
                <?php foreach ($cities as $c): ?>
                <option value="<?= $c['id'] ?>" <?= ($company['city_id']==$c['id'])?'selected':'' ?>>
                    <?= htmlspecialchars($c['name']) ?>
                </option>
                <?php endforeach; ?>
            </select>

            <label>عن الشركة</label>
            <textarea name="about" rows="3"><?= htmlspecialchars($company['about'] ?? '') ?></textarea>

            <label>الهاتف</label>
            <input type="text" name="phone" value="<?= htmlspecialchars($company['phone'] ?? '') ?>">

            <label>رقم الواتساب</label>
            <input type="text" name="whatsapp" value="<?= htmlspecialchars($company['whatsapp'] ?? '') ?>">

            <label>البريد الإلكتروني</label>
            <input type="email" name="email" value="<?= htmlspecialchars($company['email'] ?? '') ?>">

            <label>رابط الموقع</label>
            <input type="url" name="website" placeholder="https://example.com" value="<?= htmlspecialchars($company['website'] ?? '') ?>">

            <label>رابط الموقع على الخريطة</label>
            <input type="url" name="map_link" placeholder="https://goo.gl/maps/..." value="<?= htmlspecialchars($company['map_link'] ?? '') ?>">

            <label>الشعار الحالي</label>
            <div class="img-row">
                <?php if (!empty($company['logo'])): ?>
                    <img src="../<?= htmlspecialchars($company['logo']) ?>" class="img-thumb" alt="الشعار">
                <?php else: ?>
                    <span style="color:#bbb;">لا يوجد شعار</span>
                <?php endif; ?>
            </div>
            <input type="file" name="logo" accept="image/*">

            <label>صورة الغلاف الحالية</label>
            <div class="img-row">
                <?php if (!empty($company['cover'])): ?>
                    <img src="../<?= htmlspecialchars($company['cover']) ?>" class="img-thumb" alt="غلاف">
                <?php else: ?>
                    <span style="color:#bbb;">لا يوجد غلاف</span>
                <?php endif; ?>
            </div>
            <input type="file" name="cover" accept="image/*">

            <label>صور إضافية</label>
            <div class="img-row">
                <?php foreach ($image_list as $img): ?>
                    <div class="img-box">
                        <img src="../<?= htmlspecialchars($img) ?>" class="img-thumb" alt="صورة">
                        <a href="?id=<?= $company_id ?>&delete_image=<?= urlencode($img) ?>" class="img-delete-btn" onclick="return confirm('تأكيد حذف الصورة؟');">
                            <i class="fa fa-trash"></i>
                        </a>
                    </div>
                <?php endforeach; ?>
            </div>
            <input type="file" name="images[]" multiple accept="image/*">

            <label>الحالة</label>
            <select name="status">
                <option value="pending" <?= ($company['status']=='pending')?'selected':'' ?>>بانتظار الموافقة</option>
                <option value="approved" <?= ($company['status']=='approved')?'selected':'' ?>>معتمدة</option>
                <option value="inactive" <?= ($company['status']=='inactive')?'selected':'' ?>>غير فعالة</option>
            </select>
            <div class="form-actions">
                <button class="btn-main" type="submit"><i class="fa fa-save"></i> حفظ التعديلات</button>
            </div>
        </form>
    </div>
</body>
</html>
