<?php
/**
 * Image Upload Handler
 * Handles file uploads for services, team, blog, and gallery
 */

require_once 'config.php';
session_start();

// Check if user is admin/staff
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_type'], ['admin', 'staff'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check if file was uploaded
if (!isset($_FILES['image'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No file uploaded']);
    exit();
}

$file = $_FILES['image'];
$type = isset($_GET['type']) ? $_GET['type'] : 'gallery';

// Allowed file types
$allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
$max_size = 5 * 1024 * 1024; // 5MB

// Validate file
if (!in_array($file['type'], $allowed_types)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid file type. Only images allowed.']);
    exit();
}

if ($file['size'] > $max_size) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'File too large. Maximum 5MB allowed.']);
    exit();
}

if ($file['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Upload error: ' . $file['error']]);
    exit();
}

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

// Create type-specific directories
$type_dir = $upload_dir . $type . '/';
if (!is_dir($type_dir)) {
    mkdir($type_dir, 0755, true);
}

// Generate unique filename
$file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$unique_name = $type . '_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
$file_path = $type_dir . $unique_name;

// Move uploaded file
if (move_uploaded_file($file['tmp_name'], $file_path)) {
    // Return relative path for database storage
    $relative_path = str_replace('\\', '/', $file_path);
    
    echo json_encode([
        'success' => true,
        'message' => 'Image uploaded successfully',
        'file_path' => $relative_path,
        'file_url' => $relative_path
    ]);
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to move uploaded file']);
    exit();
}
?>
