<?php
/**
 * API: تحديث حالة طلب التوظيف
 * POST /api/admin/endpoints/update_application_status.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']) || !isset($input['status'])) {
    echo json_encode(['success' => false, 'message' => 'بيانات غير مكتملة']);
    exit;
}

$id = (int)$input['id'];
$status = $input['status'];
$notes = $input['notes'] ?? null;

// التحقق من صحة الحالة
$validStatuses = ['pending', 'approved', 'rejected'];
if (!in_array($status, $validStatuses)) {
    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();
    
    // تحديث حالة الطلب في job_applications
    $query = "UPDATE job_applications 
              SET status = :status, 
                  processed_at = NOW(),
                  reviewer_notes = :notes
              WHERE id = :id";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([
        ':status' => $status,
        ':notes' => $notes,
        ':id' => $id
    ]);
    
    // إذا تمت الموافقة، نقوم بإنشاء حساب فاحص في جدول inspectors
    if ($status === 'approved') {
        // جلب بيانات المتقدم
        $getApplicant = $pdo->prepare("SELECT * FROM job_applications WHERE id = :id");
        $getApplicant->execute([':id' => $id]);
        $applicant = $getApplicant->fetch(PDO::FETCH_ASSOC);
        
        if ($applicant) {
            // التحقق من وجود المستخدم في جدول users
            $checkUser = $pdo->prepare("SELECT id FROM users WHERE email = :email OR phone = :phone");
            $checkUser->execute([
                ':email' => $applicant['email'],
                ':phone' => $applicant['phone']
            ]);
            $user = $checkUser->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                // إضافة الفاحص في جدول inspectors
                $insertInspector = $pdo->prepare("INSERT INTO inspectors (
                    user_id, full_name, phone, email, specialization, 
                    region, experience_years, status, created_at
                ) VALUES (
                    :user_id, :full_name, :phone, :email, :specialization,
                    :region, :experience_years, 'available', NOW()
                )");
                
                $insertInspector->execute([
                    ':user_id' => $user['id'],
                    ':full_name' => $applicant['full_name'],
                    ':phone' => $applicant['phone'],
                    ':email' => $applicant['email'],
                    ':specialization' => $applicant['job_role'] === 'inspector' ? 'فحص شامل' : 'متدرب',
                    ':region' => $applicant['governorate'],
                    ':experience_years' => $applicant['years_experience'] ?? $applicant['experience_years'] ?? 0
                ]);
            }
        }
    }
    
    $pdo->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'تم تحديث الحالة بنجاح',
        'data' => [
            'id' => $id,
            'status' => $status
        ]
    ], 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);
}
?>