<?php
/**
 * Simple Image Upload API
 * Method: POST (multipart/form-data)
 */

// Start session
session_start();

// Include database connection
require_once '../controlls/functions.php';

// Set response headers
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

/**
 * Send JSON response
 */
function sendResponse($success, $message, $data = null) {
    $response = array(
        'success' => (bool)$success,
        'message' => $message
    );
    
    if ($data !== null) {
        $response['data'] = $data;
    }
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit();
}

/**
 * Check if user is logged in
 */
function checkAuth() {
    if (!isset($_SESSION['user_login'])) {
        sendResponse(false, 'Authentication required');
    }
    return $_SESSION['user_login'];
}

// Check authentication
$user = checkAuth();

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST method is allowed');
}

// Define upload directory
$upload_dir = '../uploads/products/';

// Create directory if it doesn't exist
if (!file_exists($upload_dir)) {
    if (!mkdir($upload_dir, 0755, true)) {
        sendResponse(false, 'Failed to create upload directory');
    }
}

// Check if files were uploaded
if (!isset($_FILES['images']) || empty($_FILES['images']['name'][0])) {
    sendResponse(false, 'No files uploaded');
}

// Allowed file types
$allowed_types = array('image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp');
$max_file_size = 5 * 1024 * 1024; // 5MB
$max_files = 5;

$uploaded_files = array();
$errors = array();

// Process each file
$files = $_FILES['images'];
$file_count = count($files['name']);

if ($file_count > $max_files) {
    sendResponse(false, "Maximum $max_files files allowed");
}

for ($i = 0; $i < $file_count; $i++) {
    // Skip if no file
    if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) {
        continue;
    }
    
    // Check for upload errors
    if ($files['error'][$i] !== UPLOAD_ERR_OK) {
        $errors[] = "Error uploading file: " . $files['name'][$i];
        continue;
    }
    
    $file_name = $files['name'][$i];
    $file_tmp = $files['tmp_name'][$i];
    $file_size = $files['size'][$i];
    $file_type = $files['type'][$i];
    
    // Validate file type
    if (!in_array($file_type, $allowed_types)) {
        $errors[] = "Invalid file type for: $file_name. Only JPG, PNG, GIF, WEBP allowed";
        continue;
    }
    
    // Validate file size
    if ($file_size > $max_file_size) {
        $errors[] = "File too large: $file_name. Maximum 5MB allowed";
        continue;
    }
    
    // Validate image
    $image_info = getimagesize($file_tmp);
    if ($image_info === false) {
        $errors[] = "Invalid image file: $file_name";
        continue;
    }
    
    // Generate unique filename
    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
    $new_filename = 'product_' . time() . '_' . uniqid() . '.' . $file_extension;
    $destination = $upload_dir . $new_filename;
    
    // Move uploaded file
    if (move_uploaded_file($file_tmp, $destination)) {
        $uploaded_files[] = array(
            'original_name' => $file_name,
            'saved_name' => $new_filename,
            'url' => 'uploads/products/' . $new_filename,
            'size' => $file_size,
            'type' => $file_type,
            'dimensions' => array(
                'width' => $image_info[0],
                'height' => $image_info[1]
            )
        );
    } else {
        $errors[] = "Failed to move file: $file_name";
    }
}

// Send response
if (!empty($uploaded_files)) {
    $response_data = array(
        'uploaded_files' => $uploaded_files,
        'total_uploaded' => count($uploaded_files)
    );
    
    if (!empty($errors)) {
        $response_data['errors'] = $errors;
    }
    
    sendResponse(true, 'Files uploaded successfully', $response_data);
} else {
    sendResponse(false, 'No files were uploaded', array('errors' => $errors));
}