<?php
session_start();

// Check if user is staff/admin
if (!isset($_SESSION['user_role']) || !in_array((string)$_SESSION['user_role'], ['admin', 'staff'], true)) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

// Check if image file is uploaded
if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'No image file uploaded or upload error']);
    exit;
}

$file = $_FILES['image'];
$title = $_POST['title'] ?? 'Service Image';

// Validate file type
$allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
if (!in_array($file['type'], $allowed_types)) {
    echo json_encode(['success' => false, 'message' => 'Invalid file type. Only JPG, PNG, GIF, and WebP are allowed']);
    exit;
}

// Validate file size (5MB max)
$max_size = 5 * 1024 * 1024;
if ($file['size'] > $max_size) {
    echo json_encode(['success' => false, 'message' => 'File size exceeds 5MB limit']);
    exit;
}

// Create upload directory if it doesn't exist
$upload_dir = __DIR__ . '/../assets/img/service/';
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0755, true);
}

// Generate unique filename
$file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$file_base = preg_replace('/[^a-z0-9_-]/i', '_', strtolower(str_replace(' ', '_', $title)));
$filename = 'service_' . time() . '_' . $file_base . '.' . $file_ext;
$filepath = $upload_dir . $filename;

// Move uploaded file
if (move_uploaded_file($file['tmp_name'], $filepath)) {
    // Return the relative path for use in HTML
    $relative_path = 'assets/img/service/' . $filename;
    echo json_encode([
        'success' => true,
        'message' => 'Image uploaded successfully',
        'image_path' => $relative_path,
        'full_path' => $filepath
    ]);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to move uploaded file']);
}
