<?php
/**
 * رفع صور الفحص
 * endpoint: POST /api/inspector/upload_images.php
 */

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

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

require_once '../config/database.php';
require_once 'includes/auth.php';

$user = validateToken();
$inspectorId = $user['inspector_id'];

$taskId = $_POST['task_id'] ?? 0;
$type = $_POST['type'] ?? 'general'; // general, damage, before, after

if (!$taskId) {
    http_response_code(400);
    echo json_encode(['error' => 'معرف المهمة مطلوب']);
    exit();
}

// إنشاء مجلد التحميلات إذا لم يكن موجوداً
$uploadDir = __DIR__ . '/../../uploads/inspections/' . $taskId . '/';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$uploadedFiles = [];

foreach ($_FILES as $key => $file) {
    if ($file['error'] === UPLOAD_ERR_OK) {
        $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
        $fileName = $type . '_' . time() . '_' . rand(1000, 9999) . '.' . $extension;
        $filePath = $uploadDir . $fileName;
        
        if (move_uploaded_file($file['tmp_name'], $filePath)) {
            $uploadedFiles[] = [
                'original_name' => $file['name'],
                'saved_name' => $fileName,
                'path' => '/uploads/inspections/' . $taskId . '/' . $fileName,
                'size' => $file['size'],
                'type' => $type
            ];
        }
    }
}

if (empty($uploadedFiles)) {
    http_response_code(400);
    echo json_encode(['error' => 'لم يتم رفع أي ملف']);
    exit();
}

// حفظ معلومات الصور في قاعدة البيانات
try {
    $database = new Database();
    $db = $database->getConnection();
    
    $stmt = $db->prepare("
        INSERT INTO inspection_images (request_id, image_path, image_type, uploaded_by, uploaded_at) 
        VALUES (:request_id, :image_path, :image_type, :uploaded_by, NOW())
    ");
    
    foreach ($uploadedFiles as $file) {
        $stmt->execute([
            ':request_id' => $taskId,
            ':image_path' => $file['path'],
            ':image_type' => $file['type'],
            ':uploaded_by' => $inspectorId
        ]);
    }
    
    echo json_encode([
        'success' => true,
        'uploaded_files' => $uploadedFiles,
        'message' => 'تم رفع ' . count($uploadedFiles) . ' صور بنجاح'
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في حفظ معلومات الصور: ' . $e->getMessage()]);
}
?>