<?php
/**
 * Image Upload API with QR Code Generation
 * Handles image upload, saves to uploads/images/, generates QR code, and stores data in database
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'connect.php';
require_once 'qrcode_generator.php';

/**
 * Create upload directories if they don't exist
 */
function createUploadDirectories() {
    $directories = ['uploads/images', 'uploads/qrcodes'];
    
    foreach ($directories as $dir) {
        if (!is_dir($dir)) {
            if (!mkdir($dir, 0755, true)) {
                return false;
            }
        }
    }
    return true;
}

/**
 * Validate uploaded image file
 */
function validateImage($file) {
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $maxSize = 10 * 1024 * 1024; // 10MB
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return ['valid' => false, 'error' => 'Upload error occurred'];
    }
    
    if ($file['size'] > $maxSize) {
        return ['valid' => false, 'error' => 'File too large (max 10MB)'];
    }
    
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    if (!in_array($mimeType, $allowedTypes)) {
        return ['valid' => false, 'error' => 'Invalid file type. Only JPEG, PNG, GIF, and WebP allowed'];
    }
    
    return ['valid' => true, 'mime_type' => $mimeType];
}

/**
 * Generate unique filename
 */
function generateUniqueFilename($originalName) {
    $extension = pathinfo($originalName, PATHINFO_EXTENSION);
    return uniqid('img_', true) . '.' . strtolower($extension);
}

/**
 * Save image to uploads/images directory
 */
function saveImage($file, $filename) {
    $targetPath = 'uploads/images/' . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        return $targetPath;
    }
    
    return false;
}

/**
 * Generate QR code for the view link
 */
function generateQRCode($link, $imageId) {
    $qrFilename = 'qr_' . $imageId . '_' . uniqid() . '.png';
    $qrPath = 'uploads/qrcodes/' . $qrFilename;
    
    try {
        // Use our custom QR generator
        $result = SimpleQRGenerator::generate($link, $qrPath, 300);
        
        if ($result['success']) {
            return [
                'success' => true, 
                'filename' => $result['filename'], 
                'path' => $result['path']
            ];
        }
        
        return ['success' => false, 'error' => $result['error']];
    } catch (Exception $e) {
        error_log('QR code generation failed: ' . $e->getMessage());
        return ['success' => false, 'error' => 'QR code generation failed'];
    }
}

// Main API logic
try {
    // Check if request method is POST
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
        exit;
    }
    
    // Create upload directories
    if (!createUploadDirectories()) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to create upload directories']);
        exit;
    }
    
    // Check if file was uploaded
    if (!isset($_FILES['image']) || empty($_FILES['image']['name'])) {
        http_response_code(400);
        echo json_encode(['error' => 'No image file provided']);
        exit;
    }
    
    $uploadedFile = $_FILES['image'];
    
    // Validate image
    $validation = validateImage($uploadedFile);
    if (!$validation['valid']) {
        http_response_code(400);
        echo json_encode(['error' => $validation['error']]);
        exit;
    }
    
    // Generate unique filename
    $filename = generateUniqueFilename($uploadedFile['name']);
    
    // Save image
    $imagePath = saveImage($uploadedFile, $filename);
    if (!$imagePath) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to save image']);
        exit;
    }
    
    // Check database connection
    if (!checkConnection($con)) {
        http_response_code(500);
        echo json_encode(['error' => 'Database connection failed']);
        exit;
    }
    
    // Insert image data into database
    $stmt = $con->prepare("
        INSERT INTO images (filename, original_name, file_path, file_size, mime_type) 
        VALUES (?, ?, ?, ?, ?)
    ");
    
    $stmt->execute([
        $filename,
        $uploadedFile['name'],
        $imagePath,
        $uploadedFile['size'],
        $validation['mime_type']
    ]);
    
    $imageId = $con->lastInsertId();
    
    // Generate view link
    $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . 
               '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);
    $viewLink = $baseUrl . '/view.php?id=' . $imageId;
    
    // Generate QR code
    $qrResult = generateQRCode($viewLink, $imageId);
    if (!$qrResult['success']) {
        // If QR generation fails, we still return success for the image upload
        // but note the QR code failure
        echo json_encode([
            'success' => true,
            'message' => 'Image uploaded successfully, but QR code generation failed',
            'image_id' => $imageId,
            'view_link' => $viewLink,
            'qr_error' => $qrResult['error']
        ]);
        exit;
    }
    
    // Insert QR code data into database
    $qrStmt = $con->prepare("
        INSERT INTO qr_codes (image_id, qr_filename, qr_path, view_link) 
        VALUES (?, ?, ?, ?)
    ");
    
    $qrStmt->execute([
        $imageId,
        $qrResult['filename'],
        $qrResult['path'],
        $viewLink
    ]);
    
    // Return simplified success response
    echo json_encode([
        'success' => true,
        'QRcode' => $baseUrl . '/qr.php?id=' . $imageId
    ]);
    
} catch (PDOException $e) {
    error_log('Database error in upload.php: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Database error occurred']);
    
} catch (Exception $e) {
    error_log('General error in upload.php: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'An unexpected error occurred']);
}
?>
