<?php
/**
 * طلب صلاحية جديدة من الفاحص
 * endpoint: POST /api/inspector/request_permission.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);

$permissionType = $data['permission_type'] ?? '';
$reason = $data['reason'] ?? '';

if (empty($permissionType) || empty($reason)) {
    http_response_code(400);
    echo json_encode(['error' => 'نوع الصلاحية والسبب مطلوبان']);
    exit();
}

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