<?php
// --- SETUP AND INCLUDES ---
ini_set('display_errors', 1);
error_reporting(E_ALL);
header("Content-Type: application/json; charset=UTF-8");
require_once '../config/cors.php';
require_once '../config/database.php';

// --- CONSTANTS AND CONFIGURATION ---
define('UPLOAD_DIR', __DIR__ . '/../uploads/categories/');
// --- CONFIG CHANGE: Increased file size limit to 50MB ---
define('MAX_FILE_SIZE', 50 * 1024 * 1024); // 50 MB
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

// --- DATABASE CONNECTION ---
$database = new Database();
$db = $database->getConnection();

// --- HELPER FUNCTIONS ---
function getImageUrl($imageName) {
    if (empty($imageName)) {
        return null;
    }
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'];
    $baseUrl = $protocol . $host . str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(UPLOAD_DIR));
    return $baseUrl . '/' . $imageName;
}

// --- LOGIC CHANGE: Added a function to automatically create a URL-friendly slug ---
function createSlug($string) {
   $string = strtolower(trim($string));
   // Replace non-letter or digits with a hyphen
   $string = preg_replace('~[^\pL\d]+~u', '-', $string);
   // Transliterate characters to ASCII
   $string = iconv('utf-8', 'us-ascii//TRANSLIT', $string);
   // Remove unwanted characters
   $string = preg_replace('~[^-\w]+~', '', $string);
   // Remove duplicate hyphens
   $string = preg_replace('~-+~', '-', $string);
   // Remove leading/trailing hyphens
   $string = trim($string, '-');
   if (empty($string)) {
       return 'n-a-' . uniqid();
   }
   return $string;
}


// --- ENSURE UPLOAD DIRECTORY EXISTS ---
if (!is_dir(UPLOAD_DIR)) {
    if (!mkdir(UPLOAD_DIR, 0775, true)) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Failed to create upload directory.']);
        exit;
    }
}

// --- HTTP METHOD ROUTING ---
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        // (GET logic remains the same)
        try {
            $stmt = $db->prepare("SELECT c.*, COUNT(p.id) as product_count FROM categories c LEFT JOIN products p ON c.id = p.category_id GROUP BY c.id ORDER BY c.created_at DESC");
            $stmt->execute();
            $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            foreach ($categories as &$category) {
                $category['status'] = (bool)$category['status'];
                $category['product_count'] = (int)$category['product_count'];
                $category['image_url'] = getImageUrl($category['image_url']);
            }
            
            http_response_code(200);
            echo json_encode(['success' => true, 'categories' => $categories]);

        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    case 'POST':
        $data = $_POST;

        // --- LOGIC CHANGE: Only the 'name' is required now ---
        if (empty($data['name'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Category name is required.']);
            exit;
        }
        
        // --- LOGIC CHANGE: Generate the slug automatically from the name ---
        $slug = createSlug($data['name']);

        $newImageName = null;
        $oldImageName = null;

        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            if ($_FILES['image']['size'] > MAX_FILE_SIZE) {
                http_response_code(400);
                // --- CONFIG CHANGE: Updated error message ---
                echo json_encode(['success' => false, 'error' => 'Image file is too large. Max 50MB.']);
                exit;
            }
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $_FILES['image']['tmp_name']);
            finfo_close($finfo);
            if (!in_array($mime, $allowedMimeTypes)) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Invalid image file type.']);
                exit;
            }
            $extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $newImageName = uniqid('cat_', true) . '.' . strtolower($extension);
            if (!move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR . $newImageName)) {
                http_response_code(500);
                echo json_encode(['success' => false, 'error' => 'Failed to save uploaded image.']);
                exit;
            }
        }
        
        try {
            if (isset($data['id']) && !empty($data['id'])) {
                // --- UPDATE LOGIC ---
                $id = $data['id'];

                if ($newImageName) {
                    $stmt = $db->prepare("SELECT image_url FROM categories WHERE id = :id");
                    $stmt->execute([':id' => $id]);
                    $oldImageName = $stmt->fetchColumn();
                }

                $status = isset($data['status']) && $data['status'] == '1' ? 1 : 0;
                
                $sql = "UPDATE categories SET name = :name, slug = :slug, description = :description, status = :status";
                $params = [
                    ':id' => $id,
                    ':name' => htmlspecialchars(strip_tags($data['name'])),
                    ':slug' => $slug, // Use the auto-generated slug
                    ':description' => isset($data['description']) ? htmlspecialchars(strip_tags($data['description'])) : null,
                    ':status' => $status
                ];

                if ($newImageName) {
                    $sql .= ", image_url = :image_url";
                    $params[':image_url'] = $newImageName;
                }
                
                $sql .= " WHERE id = :id";
                
                $stmt = $db->prepare($sql);
                $stmt->execute($params);

                if ($oldImageName && file_exists(UPLOAD_DIR . $oldImageName)) {
                    unlink(UPLOAD_DIR . $oldImageName);
                }

                http_response_code(200);
                echo json_encode(['success' => true, 'message' => 'Category updated successfully.']);

            } else {
                // --- CREATE LOGIC ---
                $status = isset($data['status']) && $data['status'] == '1' ? 1 : 0;
                
                $sql = "INSERT INTO categories (name, slug, description, image_url, status) VALUES (:name, :slug, :description, :image_url, :status)";
                $stmt = $db->prepare($sql);
                
                $stmt->execute([
                    ':name' => htmlspecialchars(strip_tags($data['name'])),
                    ':slug' => $slug, // Use the auto-generated slug
                    ':description' => isset($data['description']) ? htmlspecialchars(strip_tags($data['description'])) : null,
                    ':image_url' => $newImageName,
                    ':status' => $status
                ]);
                
                http_response_code(201);
                echo json_encode(['success' => true, 'message' => 'Category created successfully.', 'id' => $db->lastInsertId()]);
            }
        } catch (PDOException $e) {
            // (Error handling remains the same)
            if ($newImageName && file_exists(UPLOAD_DIR . $newImageName)) { 
                unlink(UPLOAD_DIR . $newImageName); 
            }
            if ($e->errorInfo[1] == 1062) { 
                http_response_code(409); 
                echo json_encode(['success' => false, 'error' => 'This name or slug is already in use.']); 
            } else { 
                http_response_code(500); 
                echo json_encode(['success' => false, 'error' => 'Database operation failed: ' . $e->getMessage()]); 
            }
        }
        break;

    case 'DELETE':
        // (DELETE logic remains the same)
        $data = json_decode(file_get_contents('php://input'), true);
        $id = $data['id'] ?? null;

        if (!$id) { 
            http_response_code(400); 
            echo json_encode(['success' => false, 'error' => 'Category ID is required.']); 
            exit; 
        }

        try {
            $checkStmt = $db->prepare("SELECT COUNT(*) FROM products WHERE category_id = :id");
            $checkStmt->execute([':id' => $id]);
            if ($checkStmt->fetchColumn() > 0) { 
                http_response_code(409); 
                echo json_encode(['success' => false, 'error' => 'Cannot delete. Category has associated products.']); 
                exit; 
            }
            $stmt = $db->prepare("SELECT image_url FROM categories WHERE id = :id");
            $stmt->execute([':id' => $id]);
            $imageToDelete = $stmt->fetchColumn();
            $stmt = $db->prepare("DELETE FROM categories WHERE id = :id");
            $stmt->execute([':id' => $id]);
            
            if ($stmt->rowCount() > 0) {
                if ($imageToDelete && file_exists(UPLOAD_DIR . $imageToDelete)) {
                    unlink(UPLOAD_DIR . $imageToDelete);
                }
                http_response_code(200);
                echo json_encode(['success' => true, 'message' => 'Category deleted successfully.']);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'error' => 'Category not found.']);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Failed to delete category: ' . $e->getMessage()]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Method Not Allowed']);
        break;
}
?>