<?php
/**
 * الحصول على هاش البلوكشين لتقرير الفحص
 * endpoint: GET /api/inspector/get_blockchain_hash.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, 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 = $_GET['task_id'] ?? 0;

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // التحقق من صلاحية الفاحص
    $stmt = $db->prepare("
        SELECT ir.request_number, ir.status, ir.inspector_id
        FROM inspection_requests ir
        WHERE ir.id = :id
    ");
    $stmt->execute([':id' => $taskId]);
    $task = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$task || $task['inspector_id'] != $inspectorId) {
        http_response_code(403);
        echo json_encode(['error' => 'لا يمكنك الوصول إلى هذا التقرير']);
        exit();
    }
    
    // جلب هاش البلوكشين
    $stmt = $db->prepare("
        SELECT blockchain_hash, submitted_at, accuracy, duration_minutes
        FROM inspection_records
        WHERE request_id = :request_id
        ORDER BY submitted_at DESC
        LIMIT 1
    ");
    $stmt->execute([':request_id' => $taskId]);
    $record = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$record) {
        echo json_encode([
            'success' => true,
            'verified' => false,
            'message' => 'لم يتم العثور على سجل بلوكشين لهذا الفحص'
        ]);
        exit();
    }
    
    echo json_encode([
        'success' => true,
        'verified' => true,
        'blockchain_hash' => $record['blockchain_hash'],
        'submitted_at' => $record['submitted_at'],
        'accuracy' => round($record['accuracy'], 1),
        'duration' => $record['duration_minutes'],
        'verification_url' => 'https://blockchain.autotester.com/verify/' . $record['blockchain_hash']
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>