<?php
/**
 * تسجيل دخول الفاحص
 * endpoint: POST /api/inspector/login.php
 */

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

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

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

$data = json_decode(file_get_contents('php://input'), true);

$email = $data['email'] ?? '';
$password = $data['password'] ?? '';

if (empty($email) || empty($password)) {
    http_response_code(400);
    echo json_encode(['error' => 'البريد الإلكتروني وكلمة المرور مطلوبان']);
    exit();
}

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // البحث عن المستخدم
    $stmt = $db->prepare("
        SELECT u.*, i.id as inspector_id, i.full_name, i.experience_points, i.rank 
        FROM users u
        JOIN inspectors i ON u.id = i.user_id
        WHERE u.email = :email AND u.role = 'inspector' AND u.is_active = 1
    ");
    $stmt->execute([':email' => $email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user || !password_verify($password, $user['password_hash'])) {
        http_response_code(401);
        echo json_encode(['error' => 'بيانات الدخول غير صحيحة']);
        exit();
    }
    
    // جلب صلاحيات الفاحص
    $stmt = $db->prepare("
        SELECT permission_type 
        FROM inspector_permissions 
        WHERE inspector_id = :inspector_id AND is_active = 1
    ");
    $stmt->execute([':inspector_id' => $user['inspector_id']]);
    $permissions = $stmt->fetchAll(PDO::FETCH_COLUMN);
    
    // جلب الإحصائيات
    $stmt = $db->prepare("
        SELECT 
            COUNT(*) as total_tasks,
            SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed,
            SUM(CASE WHEN status = 'pending_approval' THEN 1 ELSE 0 END) as pending,
            AVG(accuracy) as avg_accuracy
        FROM inspection_requests 
        WHERE inspector_id = :inspector_id
    ");
    $stmt->execute([':inspector_id' => $user['inspector_id']]);
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // إنشاء token
    $tokenPayload = json_encode([
        'user_id' => $user['id'],
        'inspector_id' => $user['inspector_id'],
        'role' => 'inspector',
        'exp' => time() + 86400
    ]);
    $token = base64_encode($tokenPayload);
    
    echo json_encode([
        'success' => true,
        'token' => $token,
        'user' => [
            'id' => $user['inspector_id'],
            'full_name' => $user['full_name'],
            'email' => $user['email'],
            'role' => 'inspector',
            'permissions' => $permissions,
            'experience_points' => (int)$user['experience_points'],
            'rank' => $user['rank'],
            'stats' => [
                'total_tasks' => (int)($stats['total_tasks'] ?? 0),
                'completed' => (int)($stats['completed'] ?? 0),
                'pending' => (int)($stats['pending'] ?? 0),
                'accuracy' => round($stats['avg_accuracy'] ?? 0, 1)
            ]
        ]
    ]);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>