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

require_once __DIR__ . '/../../database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    $task_id = $_POST['task_id'] ?? 0;
    $checkpoint_id = $_POST['checkpoint_id'] ?? 0;
    
    if (!$task_id) {
        throw new Exception("معرف المهمة مطلوب");
    }
    
    // إنشاء مجلد للصور إذا لم يكن موجوداً
    $uploadDir = __DIR__ . '/../../../uploads/inspections/' . $task_id . '/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    
    $uploadedFiles = [];
    
    // رفع الصور
    if (isset($_FILES['images'])) {
        $files = $_FILES['images'];
        $fileCount = count($files['name']);
        
        for ($i = 0; $i < $fileCount; $i++) {
            if ($files['error'][$i] === UPLOAD_ERR_OK) {
                $extension = pathinfo($files['name'][$i], PATHINFO_EXTENSION);
                $filename = uniqid() . '_' . date('Ymd_His') . '.' . $extension;
                $filepath = $uploadDir . $filename;
                
                if (move_uploaded_file($files['tmp_name'][$i], $filepath)) {
                    $uploadedFiles[] = [
                        'original_name' => $files['name'][$i],
                        'filename' => $filename,
                        'path' => '/uploads/inspections/' . $task_id . '/' . $filename,
                        'size' => $files['size'][$i]
                    ];
                }
            }
        }
    }
    
    // إذا كان هناك checkpoint_id، نربط الصور به
    if ($checkpoint_id && !empty($uploadedFiles)) {
        $selectQuery = "SELECT image_urls FROM inspection_checkpoints WHERE id = :checkpoint_id";
        $selectStmt = $db->prepare($selectQuery);
        $selectStmt->execute(['checkpoint_id' => $checkpoint_id]);
        $checkpoint = $selectStmt->fetch(PDO::FETCH_ASSOC);
        
        $existingImages = json_decode($checkpoint['image_urls'] ?? '[]', true);
        $allImages = array_merge($existingImages, $uploadedFiles);
        
        $updateQuery = "UPDATE inspection_checkpoints SET image_urls = :image_urls WHERE id = :checkpoint_id";
        $updateStmt = $db->prepare($updateQuery);
        $updateStmt->execute([
            'checkpoint_id' => $checkpoint_id,
            'image_urls' => json_encode($allImages)
        ]);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'تم رفع الصور بنجاح',
        'files' => $uploadedFiles
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>