<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/config.php';

$page_title = 'تعديل التصنيف';

$upload_directory = __DIR__ . '/../uploads/categories/';
$upload_db_path   = 'uploads/categories/';

if (!is_dir($upload_directory)) {
    mkdir($upload_directory, 0777, true);
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : (int)($_POST['id'] ?? 0);
if ($id <= 0) {
    header('Location: list.php?message=not_found');
    exit;
}

$stmt = $conn->prepare("SELECT id, name, image, sort_order, status FROM categories WHERE id = ? LIMIT 1");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$category = $result->fetch_assoc();

if (!$category) {
    header('Location: list.php?message=not_found');
    exit;
}

$name = $category['name'];
$sort_order = (int)$category['sort_order'];
$status = (int)$category['status'];
$current_image = $category['image'];
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $status = isset($_POST['status']) ? 1 : 0;
    $delete_current_image = isset($_POST['delete_current_image']) ? 1 : 0;
    $new_image_path = $current_image;

    if ($name === '') {
        $error_message = 'اسم التصنيف مطلوب.';
    } else {
        if ($delete_current_image === 1 && !empty($current_image)) {
            $old_file = __DIR__ . '/../' . $current_image;
            if (file_exists($old_file)) {
                @unlink($old_file);
            }
            $new_image_path = '';
        }

        if (isset($_FILES['image']) && !empty($_FILES['image']['name'])) {
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
            $extension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));

            if (!in_array($extension, $allowed_extensions, true)) {
                header('Location: list.php?message=invalid_image');
                exit;
            }

            $new_file_name = 'category_' . time() . '_' . mt_rand(1000, 9999) . '.' . $extension;
            $destination = $upload_directory . $new_file_name;

            if (move_uploaded_file($_FILES['image']['tmp_name'], $destination)) {
                if (!empty($current_image)) {
                    $old_file = __DIR__ . '/../' . $current_image;
                    if (file_exists($old_file)) {
                        @unlink($old_file);
                    }
                }
                $new_image_path = $upload_db_path . $new_file_name;
            } else {
                header('Location: list.php?message=upload_failed');
                exit;
            }
        }

        $update_stmt = $conn->prepare("UPDATE categories SET name = ?, image = ?, sort_order = ?, status = ? WHERE id = ?");
        $update_stmt->bind_param("ssiii", $name, $new_image_path, $sort_order, $status, $id);

        if ($update_stmt->execute()) {
            header('Location: list.php?message=updated');
            exit;
        } else {
            $error_message = 'صار خطأ أثناء تحديث التصنيف.';
        }
    }
}

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>

<div class="page-content">

    <div class="page-header-box">
        <div>
            <h1 class="page-main-title">تعديل التصنيف</h1>
            <p class="page-main-subtitle">عدّل بيانات التصنيف والصورة والترتيب والحالة</p>
        </div>

        <div class="page-header-actions">
            <a href="list.php" class="btn btn-light-custom">
                <i class="fa-solid fa-arrow-right"></i>
                <span>الرجوع للقائمة</span>
            </a>
        </div>
    </div>

    <?php if ($error_message !== ''): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
    <?php endif; ?>

    <div class="card form-card">
        <form method="post" enctype="multipart/form-data" class="category-form">
            <input type="hidden" name="id" value="<?php echo (int)$id; ?>">

            <div class="form-grid">
                <div class="form-group">
                    <label>اسم التصنيف</label>
                    <input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($name); ?>" required>
                </div>

                <div class="form-group">
                    <label>الترتيب</label>
                    <input type="number" name="sort_order" class="form-control" value="<?php echo (int)$sort_order; ?>" min="0">
                </div>

                <div class="form-group full-width">
                    <label>الصورة الحالية</label>
                    <div class="current-image-box">
                        <?php if (!empty($current_image)): ?>
                            <img src="/app/admin/<?php echo htmlspecialchars($current_image); ?>" alt="<?php echo htmlspecialchars($name); ?>">
                        <?php else: ?>
                            <div class="current-image-placeholder">
                                <i class="fa-solid fa-image"></i>
                                <span>ماكو صورة حالياً</span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="form-group full-width">
                    <label>رفع صورة جديدة</label>
                    <input type="file" name="image" class="form-control" accept=".jpg,.jpeg,.png,.webp,.gif">
                    <small class="form-note">إذا رفعت صورة جديدة راح تستبدل القديمة مباشرة.</small>
                </div>

                <?php if (!empty($current_image)): ?>
                    <div class="form-group full-width">
                        <label class="toggle-row">
                            <input type="checkbox" name="delete_current_image" value="1">
                            <span>حذف الصورة الحالية</span>
                        </label>
                    </div>
                <?php endif; ?>

                <div class="form-group full-width">
                    <label class="toggle-row">
                        <input type="checkbox" name="status" value="1" <?php echo ($status === 1) ? 'checked' : ''; ?>>
                        <span>التصنيف مفعل</span>
                    </label>
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <i class="fa-solid fa-floppy-disk"></i>
                    <span>حفظ التعديلات</span>
                </button>

                <a href="list.php" class="btn btn-light-custom">
                    <i class="fa-solid fa-xmark"></i>
                    <span>إلغاء</span>
                </a>
            </div>
        </form>
    </div>

</div>

<style>
.page-header-box{
    display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;
    margin-bottom:24px;background:linear-gradient(135deg,#ffffff 0%,#f9fbfd 100%);
    border:1px solid #e9eef4;border-radius:22px;padding:24px;box-shadow:0 10px 25px rgba(15,23,42,0.05);
}
.page-main-title{margin:0 0 8px;font-size:30px;font-weight:800;color:#1f2937;}
.page-main-subtitle{margin:0;color:#6b7280;font-size:15px;}
.btn-light-custom{
    display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:44px;
    border-radius:14px;border:1px solid #dce6ee;background:#fff;color:#1f2937;
    text-decoration:none;padding:10px 16px;font-weight:700;transition:.2s ease;
}
.alert{
    margin-bottom:18px;padding:16px 18px;border-radius:16px;font-weight:700;
}
.alert-danger{background:#fef2f2;color:#991b1b;border:1px solid #fecaca;}
.form-card{max-width:900px;}
.form-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:18px;
}
.form-group label{
    display:block;margin-bottom:8px;font-weight:800;color:#374151;
}
.full-width{grid-column:1 / -1;}
.form-note{display:block;margin-top:8px;color:#6b7280;}
.current-image-box{
    width:100%;max-width:260px;height:220px;border-radius:20px;overflow:hidden;
    background:#f8fafc;border:1px solid #edf2f7;
    display:flex;align-items:center;justify-content:center;
}
.current-image-box img{width:100%;height:100%;object-fit:cover;display:block;}
.current-image-placeholder{
    display:flex;flex-direction:column;align-items:center;justify-content:center;
    gap:10px;color:#94a3b8;font-weight:700;
}
.current-image-placeholder i{font-size:32px;}
.toggle-row{
    display:flex !important;align-items:center;gap:10px;
    background:#f8fafc;padding:14px 16px;border-radius:14px;border:1px solid #e5edf5;
}
.form-actions{
    display:flex;gap:12px;flex-wrap:wrap;margin-top:24px;
}
@media (max-width: 991px){
    .page-main-title{font-size:24px;}
    .page-header-box{padding:18px;}
    .form-grid{grid-template-columns:1fr;}
}
</style>

<?php include __DIR__ . '/../includes/footer.php'; ?>