<?php include "../../root.class.php";
$db = new db_safeguard();

header('Content-Type: application/json');

// Get JSON input
$json = file_get_contents('php://input');
$data = json_decode($json, true);

// Validate input
if (!isset($data['base64_data']) || empty($data['base64_data'])) {
    echo json_encode([
        'success' => false,
        'message' => 'No Base64 data provided'
    ]);
    exit;
}

$base64_data = $data['base64_data'];
$mime_type = $data['mime_type'] ?? 'application/octet-stream';
$jobcard_no = $data['jobcard_no'] ?? 'UNKNOWN';
$section_name = $data['section_name'] ?? 'slip';
$file_save_path = $data['file_save_path'] ?? '../jobcards/slips/';

// Determine file extension from MIME type
$extension_map = [
    'image/jpeg' => 'jpg',
    'image/jpg' => 'jpg',
    'image/png' => 'png',
    'image/gif' => 'gif',
    'image/webp' => 'webp',
    'application/pdf' => 'pdf',
    'image/bmp' => 'bmp',
    'image/tiff' => 'tiff'
];

$extension = $extension_map[$mime_type] ?? 'bin';

// Create directory if it doesn't exist
if (!file_exists($file_save_path)) {
    mkdir($file_save_path, 0777, true);
}

// Generate unique filename
$timestamp = time();
$random = substr(md5(mt_rand()), 0, 8);
$filename = "{$jobcard_no}_{$section_name}_{$timestamp}_{$random}.{$extension}";
$full_path = $file_save_path . $filename;

// Decode Base64 and save file
try {
    $decoded_data = base64_decode($base64_data, true);
    
    if ($decoded_data === false) {
        throw new Exception('Invalid Base64 encoding');
    }
    
    // Validate file size (e.g., max 5MB)
    $max_size = 5 * 1024 * 1024; // 5MB in bytes
    if (strlen($decoded_data) > $max_size) {
        throw new Exception('File size exceeds maximum allowed (5MB)');
    }
    
    // Save file
    $result = file_put_contents($full_path, $decoded_data);
    
    if ($result === false) {
        throw new Exception('Failed to save file to disk');
    }
    
    // Optional: Verify image integrity for image files
    if (strpos($mime_type, 'image/') === 0) {
        $image_info = @getimagesize($full_path);
        if ($image_info === false) {
            unlink($full_path); // Delete invalid file
            throw new Exception('Invalid image file');
        }
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'File uploaded successfully',
        'filename' => $filename,
        'path' => $full_path,
        'size' => strlen($decoded_data),
        'mime_type' => $mime_type
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>