<?php
/**
 * File Upload API
 * فوترة بلس - POS System
 * 
 * Handles file uploads for product images, receipts, etc.
 */

require_once 'db.php';
require_once 'auth.php';

// Health check for GET requests
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    jsonResponse(true, 'Upload service is running', [
        'max_file_size' => '10MB',
        'allowed_types' => ['jpg', 'png', 'gif', 'webp', 'pdf', 'xml'],
        'upload_dir_exists' => is_dir('../uploads/'),
        'upload_dir_writable' => is_writable('../uploads/')
    ]);
}

// Check request method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Method not allowed', null, 405);
}

// Configuration
$uploadDir = '../uploads/';
$maxFileSize = 10 * 1024 * 1024; // 10MB
$allowedTypes = [
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
    'image/gif' => 'gif',
    'image/webp' => 'webp',
    'application/pdf' => 'pdf',
    'application/xml' => 'xml',
    'text/xml' => 'xml'
];

// Create upload directory if it doesn't exist
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// Check if file was uploaded
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    $errorMessages = [
        UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize',
        UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE',
        UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
        UPLOAD_ERR_EXTENSION => 'File upload stopped by extension'
    ];
    
    $errorCode = $_FILES['file']['error'] ?? UPLOAD_ERR_NO_FILE;
    $errorMessage = $errorMessages[$errorCode] ?? 'Unknown upload error';
    
    jsonResponse(false, $errorMessage, null, 400);
}

$file = $_FILES['file'];

// Validate file size
if ($file['size'] > $maxFileSize) {
    jsonResponse(false, 'File size exceeds limit (10MB)', null, 400);
}

// Validate file type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

if (!isset($allowedTypes[$mimeType])) {
    jsonResponse(false, 'File type not allowed: ' . $mimeType, null, 400);
}

// Generate unique filename
$extension = $allowedTypes[$mimeType];
$filename = generateUUID() . '.' . $extension;
$filepath = $uploadDir . $filename;

// Move uploaded file
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
    jsonResponse(false, 'Failed to save file', null, 500);
}

// Generate URL dynamically based on current script location
// This ensures the upload path always matches the API path structure
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];

// Derive upload path from current script location
// If API is at /faw/api/, uploads will be at /faw/uploads/
$scriptPath = dirname($_SERVER['SCRIPT_NAME']); // e.g., /faw/api
$basePath = dirname($scriptPath); // e.g., /faw
$uploadPath = $basePath . '/uploads/';

$baseUrl = $protocol . '://' . $host . $uploadPath;
$fileUrl = $baseUrl . $filename;

// Optional: Update database record if table and id provided
$table = $_POST['table'] ?? '';
$id = $_POST['id'] ?? '';
$field = $_POST['field'] ?? 'image_url';

if (!empty($table) && !empty($id)) {
    try {
        global $pdo;
        
        // Validate table name
        $allowedTables = ['products', 'sellers', 'employees', 'customers', 'expenses'];
        if (in_array($table, $allowedTables)) {
            $stmt = $pdo->prepare("UPDATE `$table` SET `$field` = ?, updated_at = ? WHERE id = ?");
            $stmt->execute([$fileUrl, getCurrentTimestamp(), $id]);
        }
    } catch (PDOException $e) {
        // Log error but don't fail the upload
        error_log('Failed to update database: ' . $e->getMessage());
    }
}

jsonResponse(true, 'File uploaded successfully', [
    'filename' => $filename,
    'url' => $fileUrl,
    'size' => $file['size'],
    'type' => $mimeType
], 201);
?>
