<?php
/**
 * API: تحديث بيانات فاحص
 * POST /api/admin/endpoints/update_inspector.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();
}

// إعدادات الاتصال بقاعدة البيانات
$host = "localhost";
$dbname = "digitals_autotester_db";
$username = "digitals";
$password = "bassam.bassam";

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

if (!$input || !isset($input['id'])) {
    echo json_encode(['success' => false, 'message' => 'بيانات غير مكتملة']);
    exit;
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // بدء المعاملة
    $pdo->beginTransaction();
    
    // أولاً: الحصول على user_id المرتبط بالفاحص
    $getUserIdQuery = "SELECT user_id FROM inspectors WHERE id = :id";
    $getUserIdStmt = $pdo->prepare($getUserIdQuery);
    $getUserIdStmt->execute([':id' => $input['id']]);
    $inspector = $getUserIdStmt->fetch(PDO::FETCH_ASSOC);
    $userId = $inspector['user_id'] ?? null;
    
    // تحديث بيانات المستخدم إذا كان هناك user_id مرتبط
    if ($userId && $userId > 0) {
        $userUpdateFields = [];
        $userParams = [':id' => $userId];
        
        // التحقق من وجود جدول users
        $tableCheck = $pdo->query("SHOW TABLES LIKE 'users'")->rowCount();
        if ($tableCheck > 0) {
            $userColumnsQuery = "SHOW COLUMNS FROM users";
            $userColumnsStmt = $pdo->prepare($userColumnsQuery);
            $userColumnsStmt->execute();
            $userColumns = $userColumnsStmt->fetchAll(PDO::FETCH_COLUMN);
            
            if (in_array('full_name', $userColumns) || in_array('name', $userColumns)) {
                $nameCol = in_array('full_name', $userColumns) ? 'full_name' : 'name';
                $userUpdateFields[] = "$nameCol = :full_name";
                $userParams[':full_name'] = $input['full_name'];
            }
            
            if (in_array('phone', $userColumns)) {
                $userUpdateFields[] = "phone = :phone";
                $userParams[':phone'] = $input['phone'];
            }
            
            if (in_array('email', $userColumns)) {
                $userUpdateFields[] = "email = :email";
                $userParams[':email'] = $input['email'];
            }
            
            if (!empty($userUpdateFields)) {
                $userQuery = "UPDATE users SET " . implode(", ", $userUpdateFields) . " WHERE id = :id";
                $userStmt = $pdo->prepare($userQuery);
                $userStmt->execute($userParams);
            }
        }
    }
    
    // تحديث بيانات الفاحص
    $inspUpdateFields = [];
    $inspParams = [':id' => $input['id']];
    
    $inspColumnsQuery = "SHOW COLUMNS FROM inspectors";
    $inspColumnsStmt = $pdo->prepare($inspColumnsQuery);
    $inspColumnsStmt->execute();
    $inspColumns = $inspColumnsStmt->fetchAll(PDO::FETCH_COLUMN);
    
    if (in_array('full_name', $inspColumns)) {
        $inspUpdateFields[] = "full_name = :full_name";
        $inspParams[':full_name'] = $input['full_name'];
    } elseif (in_array('name', $inspColumns)) {
        $inspUpdateFields[] = "name = :name";
        $inspParams[':name'] = $input['full_name'];
    }
    
    if (in_array('phone', $inspColumns)) {
        $inspUpdateFields[] = "phone = :phone";
        $inspParams[':phone'] = $input['phone'];
    }
    
    if (in_array('email', $inspColumns)) {
        $inspUpdateFields[] = "email = :email";
        $inspParams[':email'] = $input['email'];
    }
    
    if (in_array('specialization', $inspColumns)) {
        $inspUpdateFields[] = "specialization = :specialization";
        $inspParams[':specialization'] = $input['specialization'];
    }
    
    if (in_array('region', $inspColumns)) {
        $inspUpdateFields[] = "region = :region";
        $inspParams[':region'] = $input['region'];
    }
    
    if (in_array('experience_years', $inspColumns)) {
        $inspUpdateFields[] = "experience_years = :experience_years";
        $inspParams[':experience_years'] = $input['experience_years'] ?? 0;
    }
    
    if (in_array('max_load', $inspColumns)) {
        $inspUpdateFields[] = "max_load = :max_load";
        $inspParams[':max_load'] = $input['max_load'] ?? 5;
    }
    
    if (in_array('status', $inspColumns)) {
        $inspUpdateFields[] = "status = :status";
        $inspParams[':status'] = $input['status'] ?? 'available';
    }
    
    if (in_array('rating', $inspColumns)) {
        $inspUpdateFields[] = "rating = :rating";
        $inspParams[':rating'] = $input['rating'] ?? 0;
    }
    
    if (in_array('center_id', $inspColumns)) {
        $inspUpdateFields[] = "center_id = :center_id";
        $inspParams[':center_id'] = $input['center_id'] ?? null;
    }
    
    if (in_array('updated_at', $inspColumns)) {
        $inspUpdateFields[] = "updated_at = NOW()";
    }
    
    if (!empty($inspUpdateFields)) {
        $inspQuery = "UPDATE inspectors SET " . implode(", ", $inspUpdateFields) . " WHERE id = :id";
        $inspStmt = $pdo->prepare($inspQuery);
        $inspStmt->execute($inspParams);
    }
    
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'تم تحديث بيانات الفاحص بنجاح'
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    if (isset($pdo)) {
        $pdo->rollBack();
    }
    error_log("Database error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>