<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../models/user.php';
require_once __DIR__ . '/../models/order.php';
require_once __DIR__ . '/../models/product.php';
require_once __DIR__ . '/../models/category.php';
require_once __DIR__ . '/../models/post.php';

class AdminController {
    private $db;
    private $user;
    private $order;
    private $product;
    private $category;
    private $post;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
        $this->user = new User($this->db);
        $this->order = new Order($this->db);
        $this->product = new Product($this->db);
        $this->category = new Category($this->db);
        $this->post = new Post($this->db);
    }

    private function checkAdminAccess() {
        // Check if user is logged in and is admin
        if (!isset($_SESSION['user_id'])) {
            http_response_code(401);
            echo json_encode(['error' => 'Unauthorized']);
            exit;
        }

        $user_data = $this->user->getUserById($_SESSION['user_id']);
        if (!$user_data || $user_data['role'] !== 'admin') {
            http_response_code(403);
            echo json_encode(['error' => 'Access denied']);
            exit;
        }
    }

    public function getStats() {
        $this->checkAdminAccess();

        try {
            // Get statistics
            $all_orders = $this->order->getAllOrders();
            $total_orders = count($all_orders);
            $total_users = count($this->user->getAllUsers() ?? []);
            $all_products = count($this->product->getAll()->fetchAll(PDO::FETCH_ASSOC) ?? []);

            // Calculate total sales
            $total_sales = array_reduce($all_orders, function($total, $order) {
                return $total + $order['total_amount'];
            }, 0);

            $stats = [
                'total_orders' => $total_orders,
                'total_users' => $total_users,
                'total_products' => $all_products,
                'total_sales' => $total_sales
            ];

            http_response_code(200);
            echo json_encode($stats);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch statistics']);
        }
    }

    public function getOrders() {
        $this->checkAdminAccess();

        try {
            $orders = $this->order->getAllOrders();
            http_response_code(200);
            echo json_encode($orders);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch orders']);
        }
    }

    public function getProducts() {
        $this->checkAdminAccess();

        try {
            $stmt = $this->product->getAll();
            $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
            http_response_code(200);
            echo json_encode($products);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch products']);
        }
    }

    public function getUsers() {
        $this->checkAdminAccess();

        try {
            $users = $this->user->getAllUsers();
            http_response_code(200);
            echo json_encode($users);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch users']);
        }
    }

    public function updateOrderStatus($params) {
        $this->checkAdminAccess();

        try {
            $order_id = $params['id'] ?? null;
            $data = json_decode(file_get_contents('php://input'), true);
            $status = $data['status'] ?? null;

            if (!$order_id || !$status) {
                http_response_code(400);
                echo json_encode(['error' => 'Order ID and status are required']);
                return;
            }

            if ($this->order->updateOrderStatus($order_id, $status)) {
                http_response_code(200);
                echo json_encode(['message' => 'Order status updated successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to update order status']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update order status']);
        }
    }

    public function deleteProduct($params) {
        $this->checkAdminAccess();

        try {
            $product_id = $params['id'] ?? null;

            if (!$product_id) {
                http_response_code(400);
                echo json_encode(['error' => 'Product ID is required']);
                return;
            }

            $this->product->id = $product_id;

            // Get product data first to delete image
            $product_data = $this->product->getOne();
            if ($product_data && $this->product->delete()) {
                // Delete image file if exists
                if (!empty($product_data['image']) && file_exists('../' . $product_data['image'])) {
                    unlink('../' . $product_data['image']);
                }
                // Delete additional images
                if (!empty($product_data['additional_images']) && is_array($product_data['additional_images'])) {
                    foreach ($product_data['additional_images'] as $image) {
                        if (file_exists('../' . $image)) {
                            unlink('../' . $image);
                        }
                    }
                }

                http_response_code(200);
                echo json_encode(['message' => 'Product deleted successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to delete product']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to delete product']);
        }
    }

    public function deleteUser($params) {
        $this->checkAdminAccess();

        try {
            $user_id = $params['id'] ?? null;

            if (!$user_id) {
                http_response_code(400);
                echo json_encode(['error' => 'User ID is required']);
                return;
            }

            // Prevent deleting current admin user
            if ($user_id == $_SESSION['user_id']) {
                http_response_code(400);
                echo json_encode(['error' => 'Cannot delete current admin user']);
                return;
            }

            if ($this->user->deleteUser($user_id)) {
                http_response_code(200);
                echo json_encode(['message' => 'User deleted successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to delete user']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to delete user']);
        }
    }

    public function getBeautyBookings() {
        $this->checkAdminAccess();

        try {
            $query = "SELECT b.*, s.name as service_name, s.price as service_price, u.name as user_name
                      FROM beauty_bookings b
                      LEFT JOIN beauty_services s ON b.service_id = s.id
                      LEFT JOIN users u ON b.user_id = u.id
                      ORDER BY b.created_at DESC";
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            $bookings = $stmt->fetchAll(PDO::FETCH_ASSOC);

            http_response_code(200);
            echo json_encode($bookings);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch beauty bookings']);
        }
    }

    public function updateBeautyBookingStatus($params) {
        $this->checkAdminAccess();

        try {
            $booking_id = $params['id'] ?? null;
            $data = json_decode(file_get_contents('php://input'), true);
            $status = $data['status'] ?? null;

            if (!$booking_id || !$status) {
                http_response_code(400);
                echo json_encode(['error' => 'Booking ID and status are required']);
                return;
            }

            $query = "UPDATE beauty_bookings SET status = ? WHERE id = ?";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(1, $status);
            $stmt->bindParam(2, $booking_id);

            if ($stmt->execute()) {
                http_response_code(200);
                echo json_encode(['message' => 'Booking status updated successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to update booking status']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update booking status']);
        }
    }

    public function getBeautyServices() {
        $this->checkAdminAccess();

        try {
            $query = "SELECT * FROM beauty_services ORDER BY created_at DESC";
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            $services = $stmt->fetchAll(PDO::FETCH_ASSOC);

            http_response_code(200);
            echo json_encode($services);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch beauty services']);
        }
    }

    public function addBeautyService() {
        $this->checkAdminAccess();

        try {
            $data = json_decode(file_get_contents('php://input'), true);

            if (!isset($data['name']) || !isset($data['price']) || !isset($data['duration']) || !isset($data['description'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Name, price, duration, and description are required']);
                return;
            }

            $query = "INSERT INTO beauty_services (name, description, price, duration, category, stock_quantity, is_active, created_at, updated_at)
                      VALUES (?, ?, ?, ?, ?, ?, 1, NOW(), NOW())";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(1, $data['name']);
            $stmt->bindParam(2, $data['description']);
            $stmt->bindParam(3, $data['price']);
            $stmt->bindParam(4, $data['duration']);
            $stmt->bindParam(5, $data['category']);
            $stmt->bindParam(6, $data['stock_quantity'] ?? 0);

            if ($stmt->execute()) {
                http_response_code(201);
                echo json_encode(['message' => 'Beauty service added successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to add beauty service']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to add beauty service']);
        }
    }

    public function toggleBeautyService($params) {
        $this->checkAdminAccess();

        try {
            $service_id = $params['id'] ?? null;

            if (!$service_id) {
                http_response_code(400);
                echo json_encode(['error' => 'Service ID is required']);
                return;
            }

            $query = "UPDATE beauty_services SET is_active = NOT is_active WHERE id = ?";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(1, $service_id);

            if ($stmt->execute()) {
                http_response_code(200);
                echo json_encode(['message' => 'Beauty service status updated successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to update beauty service status']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update beauty service status']);
        }
    }

    public function updateBeautyService($params) {
        $this->checkAdminAccess();

        try {
            $service_id = $params['id'] ?? null;
            $data = json_decode(file_get_contents('php://input'), true);

            if (!$service_id) {
                http_response_code(400);
                echo json_encode(['error' => 'Service ID is required']);
                return;
            }

            $query = "UPDATE beauty_services SET name=?, description=?, price=?, duration=?, category=?, stock_quantity=?, updated_at=NOW() WHERE id=?";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(1, $data['name']);
            $stmt->bindParam(2, $data['description']);
            $stmt->bindParam(3, $data['price']);
            $stmt->bindParam(4, $data['duration']);
            $stmt->bindParam(5, $data['category']);
            $stmt->bindParam(6, $data['stock_quantity'] ?? 0);
            $stmt->bindParam(7, $service_id);

            if ($stmt->execute()) {
                http_response_code(200);
                echo json_encode(['message' => 'Beauty service updated successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to update beauty service']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update beauty service']);
        }
    }

    public function deleteBeautyService($params) {
        $this->checkAdminAccess();

        try {
            $service_id = $params['id'] ?? null;

            if (!$service_id) {
                http_response_code(400);
                echo json_encode(['error' => 'Service ID is required']);
                return;
            }

            $query = "DELETE FROM beauty_services WHERE id = ?";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(1, $service_id);

            if ($stmt->execute()) {
                http_response_code(200);
                echo json_encode(['message' => 'Beauty service deleted successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to delete beauty service']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to delete beauty service']);
        }
    }

    public function saveSocialMedia() {
        $this->checkAdminAccess();

        try {
            $data = json_decode(file_get_contents('php://input'), true);

            // Update each social media link
            $settings = [
                'whatsapp_link' => $data['whatsapp_link'] ?? '',
                'facebook_link' => $data['facebook_link'] ?? '',
                'instagram_link' => $data['instagram_link'] ?? '',
                'threads_link' => $data['threads_link'] ?? ''
            ];

            foreach ($settings as $key => $value) {
                $this->user->updateSetting($key, $value, 'string');
            }

            http_response_code(200);
            echo json_encode(['success' => true, 'message' => 'Social media links updated successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update social media links']);
        }
    }

    public function saveIdentityDesign() {
        $this->checkAdminAccess();

        try {
            $data = json_decode(file_get_contents('php://input'), true);

            // Update identity and design settings
            $settings = [
                'logo_text' => $data['logo_text'] ?? 'Roz Skin',
                'logo_image' => $data['logo_image'] ?? '',
                'primary_color' => $data['primary_color'] ?? '#7c3aed',
                'success_color' => $data['success_color'] ?? '#10b981',
                'warning_color' => $data['warning_color'] ?? '#f59e0b',
                'danger_color' => $data['danger_color'] ?? '#ef4444',
                'font_family' => $data['font_family'] ?? 'Tajawal',
                'theme_mode' => $data['theme_mode'] ?? 'light',
                'layout_style' => $data['layout_style'] ?? 'default'
            ];

            foreach ($settings as $key => $value) {
                $this->user->updateSetting($key, $value, 'string');
            }

            http_response_code(200);
            echo json_encode(['success' => true, 'message' => 'Identity and design settings updated successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update identity and design settings']);
        }
    }

    public function saveBrandColors() {
        $this->checkAdminAccess();

        try {
            $data = json_decode(file_get_contents('php://input'), true);

            // Update brand color settings
            $colorSettings = [
                'primary_color' => $data['primary_color'] ?? '#ec4899',
                'secondary_color' => $data['secondary_color'] ?? '#f472b6',
                'accent_color' => $data['accent_color'] ?? '#06b6d4',
                'success_color' => $data['success_color'] ?? '#10b981',
                'warning_color' => $data['warning_color'] ?? '#f59e0b',
                'danger_color' => $data['danger_color'] ?? '#ef4444'
            ];

            foreach ($colorSettings as $key => $value) {
                $this->user->updateSetting($key, $value, 'string');
            }

            http_response_code(200);
            echo json_encode(['success' => true, 'message' => 'Brand colors updated successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update brand colors']);
        }
    }

    public function saveHeroSection() {
        $this->checkAdminAccess();

        try {
            $data = json_decode(file_get_contents('php://input'), true);

            // Update hero section settings
            $settings = [
                'hero_title' => $data['hero_title'] ?? 'دللي بشرتك بلمسة من الطبيعة',
                'hero_description' => $data['hero_description'] ?? 'منتجات ROZ Skin للعناية الفائقة، مصنوعة بحب لتبرز جمالك الطبيعي.',
                'hero_bg_image' => $data['hero_bg_image'] ?? 'https://i.pinimg.com/736x/7f/90/f8/7f90f82844fd937101dcb5e99229b13e.jpg'
            ];

            foreach ($settings as $key => $value) {
                $this->user->updateSetting($key, $value, 'string');
            }

            http_response_code(200);
            echo json_encode(['success' => true, 'message' => 'Hero section settings updated successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update hero section settings']);
        }
    }

    public function getIdentityDesign() {
        $this->checkAdminAccess();

        try {
            $settings = [
                'logo_text' => $this->user->getSetting('logo_text') ?: 'Roz Skin',
                'logo_image' => $this->user->getSetting('logo_image') ?: '',
                'primary_color' => $this->user->getSetting('primary_color') ?: '#7c3aed',
                'success_color' => $this->user->getSetting('success_color') ?: '#10b981',
                'warning_color' => $this->user->getSetting('warning_color') ?: '#f59e0b',
                'danger_color' => $this->user->getSetting('danger_color') ?: '#ef4444',
                'font_family' => $this->user->getSetting('font_family') ?: 'Tajawal',
                'theme_mode' => $this->user->getSetting('theme_mode') ?: 'light',
                'layout_style' => $this->user->getSetting('layout_style') ?: 'default'
            ];

            http_response_code(200);
            echo json_encode(['success' => true, 'data' => $settings]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to fetch identity and design settings']);
        }
    }

    public function getIdentityProfiles() {
        $this->checkAdminAccess();

        try {
            require_once __DIR__ . '/../models/identityprofile.php';
            $identityProfile = new IdentityProfile($this->db);
            $profiles = $identityProfile->getAll()->fetchAll(PDO::FETCH_ASSOC);
            http_response_code(200);
            echo json_encode(['profiles' => $profiles]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch identity profiles']);
        }
    }

    public function addIdentityProfile() {
        $this->checkAdminAccess();

        try {
            $data = json_decode(file_get_contents('php://input'), true);

            if (!isset($data['title']) || !isset($data['description'])) {
                http_response_code(400);
                echo json_encode(['error' => 'Title and description are required']);
                return;
            }

            require_once __DIR__ . '/../models/identityprofile.php';
            $identityProfile = new IdentityProfile($this->db);

            $identityProfile->title = $data['title'];
            $identityProfile->description = $data['description'];
            $identityProfile->profile_image = $data['profile_image'] ?? '';
            $identityProfile->product_id = $data['product_id'] ?? null;
            $identityProfile->is_active = 1;

            if ($identityProfile->create()) {
                http_response_code(201);
                echo json_encode(['message' => 'Identity profile added successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to add identity profile']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to add identity profile']);
        }
    }

    public function updateIdentityProfile($params) {
        $this->checkAdminAccess();

        try {
            $profile_id = $params['id'] ?? null;
            $data = json_decode(file_get_contents('php://input'), true);

            if (!$profile_id) {
                http_response_code(400);
                echo json_encode(['error' => 'Profile ID is required']);
                return;
            }

            require_once __DIR__ . '/../models/identityprofile.php';
            $identityProfile = new IdentityProfile($this->db);
            $identityProfile->id = $profile_id;

            $identityProfile->title = $data['title'];
            $identityProfile->description = $data['description'];
            $identityProfile->profile_image = $data['profile_image'] ?? '';
            $identityProfile->product_id = $data['product_id'] ?? null;

            if ($identityProfile->update()) {
                http_response_code(200);
                echo json_encode(['message' => 'Identity profile updated successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to update identity profile']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to update identity profile']);
        }
    }

    public function deleteIdentityProfile($params) {
        $this->checkAdminAccess();

        try {
            $profile_id = $params['id'] ?? null;

            if (!$profile_id) {
                http_response_code(400);
                echo json_encode(['error' => 'Profile ID is required']);
                return;
            }

            require_once __DIR__ . '/../models/identityprofile.php';
            $identityProfile = new IdentityProfile($this->db);
            $identityProfile->id = $profile_id;

            if ($identityProfile->delete()) {
                http_response_code(200);
                echo json_encode(['message' => 'Identity profile deleted successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to delete identity profile']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to delete identity profile']);
        }
    }

    public function getPosts() {
        $this->checkAdminAccess();

        try {
            $posts = $this->post->getAll();
            http_response_code(200);
            echo json_encode(['posts' => $posts]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to fetch posts']);
        }
    }

    public function addPost() {
        $this->checkAdminAccess();

        try {
            if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
                http_response_code(400);
                echo json_encode(['error' => 'Image is required']);
                return;
            }

            $caption = $_POST['caption'] ?? '';

            // Handle image upload
            $uploadDir = __DIR__ . '/../uploads/posts/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $fileName = uniqid('post_') . '.' . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $uploadPath = $uploadDir . $fileName;

            if (!move_uploaded_file($_FILES['image']['tmp_name'], $uploadPath)) {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to upload image']);
                return;
            }

            // Save to database
            $imagePath = 'uploads/posts/' . $fileName;
            $this->post->create($caption, $imagePath);

            http_response_code(201);
            echo json_encode(['message' => 'Post added successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to add post']);
        }
    }

    public function deletePost($params) {
        $this->checkAdminAccess();

        try {
            $post_id = $params['id'] ?? null;

            if (!$post_id) {
                http_response_code(400);
                echo json_encode(['error' => 'Post ID is required']);
                return;
            }

            // Get post data first to delete image
            $post_data = $this->post->getOne($post_id);
            if ($post_data && $this->post->delete($post_id)) {
                // Delete image file if exists
                if (!empty($post_data['image']) && file_exists('../' . $post_data['image'])) {
                    unlink('../' . $post_data['image']);
                }

                http_response_code(200);
                echo json_encode(['message' => 'Post deleted successfully']);
            } else {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to delete post']);
            }
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to delete post']);
        }
    }

    public function getCategories() {
        $this->checkAdminAccess();

        try {
            $type = $_GET['type'] ?? null;
            $stmt = $this->category->readAll($type);
            $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Add item_count to each category
            foreach ($categories as &$category) {
                $this->category->id = $category['id'];
                $this->category->type = $category['type'];
                $stats = $this->category->getStats();
                $category['item_count'] = $stats['products_count'] ?? $stats['services_count'] ?? 0;
            }

            // Calculate stats
            $total_products = 0;
            $total_services = 0;
            foreach ($categories as $category) {
                if ($category['type'] == 'product') {
                    $total_products += $category['item_count'] ?? 0;
                } else {
                    $total_services += $category['item_count'] ?? 0;
                }
            }

            $result = [
                'categories' => $categories,
                'stats' => [
                    'total_products' => $total_products,
                    'total_services' => $total_services
                ]
            ];

            // Check if this is an API call or page render
            if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
                http_response_code(200);
                echo json_encode($categories);
            } else {
                return $result;
            }
        } catch (Exception $e) {
            if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to fetch categories']);
            } else {
                throw $e;
            }
        }
    }

    public function addCategory($params = []) {
        $this->checkAdminAccess();

        try {
            $data = $_POST;

            if (!isset($data['name']) || !isset($data['type'])) {
                return ['success' => false, 'message' => 'Name and type are required'];
            }

            // Handle image upload
            $image_path = '';
            if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $upload_dir = __DIR__ . '/../uploads/categories/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }

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

                if (!in_array($file_extension, $allowed_extensions)) {
                    return ['success' => false, 'message' => 'Invalid image format'];
                }

                $file_name = 'category_' . time() . '_' . uniqid() . '.' . $file_extension;
                $upload_path = $upload_dir . $file_name;

                if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
                    $image_path = 'uploads/categories/' . $file_name;
                }
            }

            $this->category->name = $data['name'];
            $this->category->description = $data['description'] ?? '';
            $this->category->image = $image_path;
            $this->category->type = $data['type'];
            $this->category->is_active = $data['is_active'] ?? true;

            if ($this->category->create()) {
                return ['success' => true, 'message' => 'Category added successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to add category'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Failed to add category'];
        }
    }

    public function updateCategory($category_id, $data, $files) {
        try {
            if (!$category_id) {
                return ['success' => false, 'message' => 'Category ID is required'];
            }

            // Get current category data
            $this->category->id = $category_id;
            $current_category = $this->category->readOne();

            // Handle image upload
            $image_path = $current_category['image'];
            if (isset($files['image']) && $files['image']['error'] === UPLOAD_ERR_OK) {
                $upload_dir = __DIR__ . '/../uploads/categories/';
                if (!is_dir($upload_dir)) {
                    mkdir($upload_dir, 0777, true);
                }

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

                if (!in_array($file_extension, $allowed_extensions)) {
                    return ['success' => false, 'message' => 'Invalid image format'];
                }

                $file_name = 'category_' . time() . '_' . uniqid() . '.' . $file_extension;
                $upload_path = $upload_dir . $file_name;

                if (move_uploaded_file($files['image']['tmp_name'], $upload_path)) {
                    $image_path = 'uploads/categories/' . $file_name;
                    // Delete old image if exists
                    if (!empty($current_category['image']) && file_exists(__DIR__ . '/../' . $current_category['image'])) {
                        unlink(__DIR__ . '/../' . $current_category['image']);
                    }
                }
            }

            $this->category->name = $data['name'];
            $this->category->description = $data['description'] ?? '';
            $this->category->image = $image_path;
            $this->category->type = $data['type'];
            $this->category->is_active = $data['is_active'] ?? true;

            if ($this->category->update()) {
                return ['success' => true, 'message' => 'Category updated successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to update category'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Failed to update category'];
        }
    }

    public function deleteCategory($params) {
        $this->checkAdminAccess();

        try {
            $category_id = $params['category_id'] ?? null;

            if (!$category_id) {
                return ['success' => false, 'message' => 'Category ID is required'];
            }

            $this->category->id = $category_id;

            // Check if category has items
            if ($this->category->hasItems()) {
                return ['success' => false, 'message' => 'Cannot delete category with existing items'];
            }

            // Get category data to delete image
            $category_data = $this->category->readOne();
            if ($category_data && $this->category->delete()) {
                // Delete image file if exists
                if (!empty($category_data['image']) && file_exists(__DIR__ . '/../' . $category_data['image'])) {
                    unlink(__DIR__ . '/../' . $category_data['image']);
                }

                return ['success' => true, 'message' => 'Category deleted successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to delete category'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Failed to delete category'];
        }
    }

    public function toggleCategory($params) {
        $this->checkAdminAccess();

        try {
            $category_id = $params['category_id'] ?? null;

            if (!$category_id) {
                return ['success' => false, 'message' => 'Category ID is required'];
            }

            $this->category->id = $category_id;

            if ($this->category->toggleActive()) {
                return ['success' => true, 'message' => 'Category status updated successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to update category status'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Failed to update category status'];
        }
    }
}
?>