<?php
// api/assign-inspector.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');

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

$host = 'localhost';
$dbname = 'digitals_autotester_db';
$username = 'digitals';
$password = 'bassam.bassam';

try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في الاتصال بقاعدة البيانات']);
    exit;
}

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

if (!$data) {
    echo json_encode(['success' => false, 'message' => 'بيانات غير صالحة']);
    exit;
}

$required = ['name', 'email', 'phone', 'role', 'grade', 'governorate', 'area', 'maxDaily'];
foreach ($required as $field) {
    if (empty($data[$field])) {
        echo json_encode(['success' => false, 'message' => 'جميع الحقول المطلوبة يجب ملؤها']);
        exit;
    }
}

try {
    $pdo->beginTransaction();
    
    // 1. تحديث حالة طلب التوظيف إذا كان موجوداً
    if (!empty($data['requestId'])) {
        $checkTable = $pdo->query("SHOW TABLES LIKE 'job_applications'");
        if ($checkTable->rowCount() > 0) {
            $stmt = $pdo->prepare("UPDATE job_applications SET status = 'approved', processed_at = NOW() WHERE id = ?");
            $stmt->execute([$data['requestId']]);
        }
    }
    
    // 2. إنشاء اسم مستخدم فريد
    $baseUsername = strtolower(preg_replace('/[^a-zA-Z0-9]/', '', explode('@', $data['email'])[0]));
    $username = $baseUsername;
    $counter = 1;
    
    while (true) {
        $check = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $check->execute([$username]);
        if (!$check->fetch()) {
            break;
        }
        $username = $baseUsername . $counter;
        $counter++;
    }
    
    // 3. إنشاء كلمة مرور مؤقتة
    $tempPassword = bin2hex(random_bytes(4));
    $hashedPassword = password_hash($tempPassword, PASSWORD_DEFAULT);
    
    // 4. إدراج المستخدم الجديد
    $stmt = $pdo->prepare("
        INSERT INTO users (username, full_name, email, phone, password, role, is_active, created_at) 
        VALUES (?, ?, ?, ?, ?, 'inspector', 1, NOW())
    ");
    $stmt->execute([
        $username,
        $data['name'],
        $data['email'],
        $data['phone'],
        $hashedPassword
    ]);
    
    $userId = $pdo->lastInsertId();
    
    // 5. إضافة بيانات الفاحص في جدول inspectors
    $checkTable = $pdo->query("SHOW TABLES LIKE 'inspectors'");
    if ($checkTable->rowCount() > 0) {
        $permissions = json_encode($data['permissions'] ?? []);
        
        $stmt = $pdo->prepare("
            INSERT INTO inspectors (user_id, specialization, grade, governorate, area, max_daily_requests, permissions, available, years_experience, created_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, NOW())
        ");
        $stmt->execute([
            $userId,
            $data['role'],
            $data['grade'],
            $data['governorate'],
            $data['area'],
            $data['maxDaily'],
            $permissions,
            $data['years_experience'] ?? null
        ]);
    }
    
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'تم تعيين الفاحص بنجاح',
        'data' => [
            'userId' => $userId,
            'username' => $username,
            'tempPassword' => $tempPassword,
            'phone' => $data['phone']
        ]
    ]);
    
} catch (PDOException $e) {
    $pdo->rollBack();
    echo json_encode(['success' => false, 'message' => 'خطأ في قاعدة البيانات: ' . $e->getMessage()]);
}
?>