<?php
/**
 * طلب دعم فني من الفاحص
 * endpoint: POST /api/inspector/request_support.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'];
$data = json_decode(file_get_contents('php://input'), true);

$issueType = $data['issue_type'] ?? '';
$description = $data['description'] ?? '';
$laneNumber = $data['lane_number'] ?? null;

if (empty($issueType) || empty($description)) {
    http_response_code(400);
    echo json_encode(['error' => 'نوع المشكلة والوصف مطلوبان']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // إضافة طلب الدعم
    $stmt = $db->prepare("
        INSERT INTO technical_support (
            inspector_id, issue_type, description, lane_number, status, created_at
        ) VALUES (
            :inspector_id, :issue_type, :description, :lane_number, 'pending', NOW()
        )
    ");
    $stmt->execute([
        ':inspector_id' => $inspectorId,
        ':issue_type' => $issueType,
        ':description' => $description,
        ':lane_number' => $laneNumber
    ]);
    $supportId = $db->lastInsertId();
    
    // إضافة إشعار للمشرف
    $stmt = $db->prepare("
        INSERT INTO notifications (user_id, type, title, message, related_id, created_at) 
        SELECT supervisor_id, 'technical_support', 'طلب دعم فني', 
        CONCAT('طلب دعم فني من الفاحص في الحارة ', :lane_number),
        :support_id, NOW()
        FROM supervisor_inspectors
        WHERE inspector_id = :inspector_id
    ");
    $stmt->execute([
        ':lane_number' => $laneNumber ?? 'غير محدد',
        ':support_id' => $supportId,
        ':inspector_id' => $inspectorId
    ]);
    
    echo json_encode([
        'success' => true,
        'support_id' => $supportId,
        'message' => 'تم إرسال طلب الدعم الفني للمشرف'
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>