<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../../config/database.php';
require_once '../../models/category.php';

$database = new Database();
$db = $database->getConnection();
$category = new Category($db);

$message = '';
$error_message = '';

// Check if we are in edit mode
$is_edit = false;
$category_id = null;
$category_data = null;

if (isset($_GET['id'])) {
    $is_edit = true;
    $category_id = $_GET['id'];
    $category->id = $category_id;
    
    if ($category->readOne()) {
        $category_data = [
            'name' => $category->name,
            'description' => $category->description,
            'image' => $category->image,
            'type' => $category->type,
            'is_active' => $category->is_active
        ];
    } else {
        header('Location: index.php?error=category_not_found');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate required fields
    $name = trim($_POST['name'] ?? '');
    $type = $_POST['type'] ?? '';
    $description = trim($_POST['description'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    $errors = [];

    if (empty($name)) {
        $errors[] = 'اسم الفئة مطلوب';
    }

    if (empty($type) || !in_array($type, ['product', 'service'])) {
        $errors[] = 'نوع الفئة مطلوب ويجب أن يكون منتج أو خدمة';
    }

    if (empty($errors)) {
        // Handle image upload
        $image_path = $is_edit ? ($category_data['image'] ?? '') : '';
        
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            // Fix: Upload to the correct directory relative to this file
            // This file is in backend/admin/categories/
            // We want to upload to backend/uploads/categories/
            $upload_dir_relative = '../../uploads/categories/';
            $upload_dir_db = 'uploads/categories/'; // Path to store in DB
            
            if (!is_dir($upload_dir_relative)) {
                mkdir($upload_dir_relative, 0777, true);
            }

            $file_extension = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

            if (!in_array($file_extension, $allowed_extensions)) {
                $error_message = 'نوع الملف غير مدعوم. يرجى اختيار صورة (JPG, PNG, GIF, WEBP)';
            } else {
                $file_name = uniqid('category_') . '.' . $file_extension;
                $upload_path = $upload_dir_relative . $file_name;

                if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
                    $image_path = $upload_dir_db . $file_name;
                } else {
                    $error_message = 'فشل في رفع الصورة';
                }
            }
        }

        if (empty($error_message)) {
            $category->name = $name;
            $category->type = $type;
            $category->description = $description;
            $category->image = $image_path;
            $category->is_active = $is_active;

            if ($is_edit) {
                $category->id = $category_id;
                if ($category->update()) {
                    $message = 'تم تحديث الفئة بنجاح!';
                    // Refresh data
                    if ($category->readOne()) {
                        $category_data = [
                            'name' => $category->name,
                            'description' => $category->description,
                            'image' => $category->image,
                            'type' => $category->type,
                            'is_active' => $category->is_active
                        ];
                    }
                } else {
                    $error_message = 'حدث خطأ أثناء تحديث الفئة';
                }
            } else {
                if ($category->create()) {
                    $message = 'تم إضافة الفئة بنجاح!';
                    header('Location: index.php?success=1');
                    exit;
                } else {
                    $error_message = 'حدث خطأ أثناء إضافة الفئة';
                }
            }
        }
    } else {
        $error_message = implode('<br>', $errors);
    }
}
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $is_edit ? 'تعديل فئة' : 'إضافة فئة جديدة'; ?> - لوحة التحكم</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@200;300;400;500;700;800;900&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        body {
            font-family: 'Tajawal', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .form-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            padding: 40px;
            margin: 20px auto;
            max-width: 600px;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            font-weight: 600;
            color: #374151;
            display: block;
            margin-bottom: 0.5rem;
        }

        .form-control {
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            padding: 12px 16px;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: #7c3aed;
            box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.1);
        }

        .btn-primary {
            background: linear-gradient(135deg, #7c3aed 0%, #a855f7 100%);
            border: none;
            border-radius: 10px;
            padding: 12px 30px;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(124, 58, 237, 0.3);
        }

        .alert {
            border-radius: 10px;
            border: none;
        }

        .image-preview {
            max-width: 200px;
            max-height: 200px;
            border-radius: 10px;
            margin-top: 10px;
            display: none;
        }

        .file-upload {
            border: 2px dashed #d1d5db;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .file-upload:hover {
            border-color: #7c3aed;
            background-color: rgba(124, 58, 237, 0.05);
        }

        .file-upload.dragover {
            border-color: #7c3aed;
            background-color: rgba(124, 58, 237, 0.1);
        }

        .switch {
            position: relative;
            display: inline-block;
            width: 60px;
            height: 34px;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked + .slider {
            background-color: #7c3aed;
        }

        input:checked + .slider:before {
            transform: translateX(26px);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="form-container">
            <div class="text-center mb-4">
                <h2 class="mb-3" style="color: #7c3aed; font-weight: 700;"><?php echo $is_edit ? 'تعديل الفئة' : 'إضافة فئة جديدة'; ?></h2>
                <p class="text-muted"><?php echo $is_edit ? 'تعديل بيانات الفئة الحالية' : 'أضف فئة جديدة للمنتجات أو الخدمات'; ?></p>
            </div>

            <?php if ($message): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle ml-2"></i><?php echo $message; ?>
                </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle ml-2"></i><?php echo $error_message; ?>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data">
                <div class="form-group">
                    <label for="name">اسم الفئة *</label>
                    <input type="text" class="form-control" id="name" name="name" required
                           value="<?php echo $is_edit ? htmlspecialchars($category_data['name']) : ''; ?>"
                           placeholder="أدخل اسم الفئة">
                </div>

                <div class="form-group">
                    <label for="type">نوع الفئة *</label>
                    <select class="form-control" id="type" name="type" required>
                        <option value="">اختر النوع</option>
                        <option value="product" <?php echo ($is_edit && $category_data['type'] === 'product') ? 'selected' : ''; ?>>منتج</option>
                        <option value="service" <?php echo ($is_edit && $category_data['type'] === 'service') ? 'selected' : ''; ?>>خدمة</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="description">وصف الفئة</label>
                    <textarea class="form-control" id="description" name="description" rows="3"
                              placeholder="أدخل وصف الفئة (اختياري)"><?php echo $is_edit ? htmlspecialchars($category_data['description']) : ''; ?></textarea>
                </div>

                <div class="form-group">
                    <label>صورة الفئة</label>
                    <div class="file-upload" id="fileUpload">
                        <i class="fas fa-cloud-upload-alt fa-2x mb-2" style="color: #7c3aed;"></i>
                        <p class="mb-1">اسحب الصورة هنا أو انقر للاختيار</p>
                        <small class="text-muted">PNG, JPG, GIF, WEBP حتى 5MB</small>
                        <input type="file" id="image" name="image" accept="image/*" style="display: none;">
                    </div>
                    <?php if ($is_edit && !empty($category_data['image'])): ?>
                        <div class="mt-2">
                            <p class="text-muted text-sm mb-1">الصورة الحالية:</p>
                            <img src="../../<?php echo htmlspecialchars($category_data['image']); ?>" class="image-preview" style="display: block;" alt="الصورة الحالية">
                        </div>
                    <?php endif; ?>
                    <img id="imagePreview" class="image-preview" src="#" alt="معاينة الصورة الجديدة">
                </div>

                <div class="form-group">
                    <label class="d-flex align-items-center">
                        <span class="mr-2">نشط</span>
                        <label class="switch">
                            <input type="checkbox" name="is_active" <?php echo (!$is_edit || $category_data['is_active']) ? 'checked' : ''; ?>>
                            <span class="slider"></span>
                        </label>
                    </label>
                    <small class="text-muted">حدد ما إذا كانت الفئة نشطة ومرئية للمستخدمين</small>
                </div>

                <div class="text-center">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="fas <?php echo $is_edit ? 'fa-save' : 'fa-plus'; ?> ml-2"></i><?php echo $is_edit ? 'حفظ التغييرات' : 'إضافة الفئة'; ?>
                    </button>
                    <a href="index.php" class="btn btn-secondary btn-lg ml-3">
                        <i class="fas fa-arrow-right ml-2"></i>العودة
                    </a>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Image upload functionality
        const fileUpload = document.getElementById('fileUpload');
        const fileInput = document.getElementById('image');
        const imagePreview = document.getElementById('imagePreview');

        fileUpload.addEventListener('click', () => {
            fileInput.click();
        });

        fileUpload.addEventListener('dragover', (e) => {
            e.preventDefault();
            fileUpload.classList.add('dragover');
        });

        fileUpload.addEventListener('dragleave', () => {
            fileUpload.classList.remove('dragover');
        });

        fileUpload.addEventListener('drop', (e) => {
            e.preventDefault();
            fileUpload.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                fileInput.files = files;
                previewImage(files[0]);
            }
        });

        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                previewImage(e.target.files[0]);
            }
        });

        function previewImage(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                imagePreview.src = e.target.result;
                imagePreview.style.display = 'block';
            };
            reader.readAsDataURL(file);
        }

        // Form validation
        document.querySelector('form').addEventListener('submit', function(e) {
            const name = document.getElementById('name').value.trim();
            const type = document.getElementById('type').value;

            if (!name) {
                e.preventDefault();
                alert('يرجى إدخال اسم الفئة');
                return;
            }

            if (!type) {
                e.preventDefault();
                alert('يرجى اختيار نوع الفئة');
                return;
            }
        });
    </script>
</body>
</html>