<?php
// ============================================
// BAITARI — Admin Vet Review API
// api/admin_vets.php
// ============================================
require_once __DIR__ . '/../includes/config.php';
session_start_secure();
header('Content-Type: application/json; charset=utf-8');

// Admin only
require_role('admin');
$admin = current_user();

$action = sanitize_str($_POST['action'] ?? $_GET['action'] ?? '');

// Router - PHP 7/8 compatible
$handlers = [
    'get_vet_details' => 'get_vet_details',
    'approve_vet' => 'approve_vet',
    'reject_vet' => 'reject_vet',
    'suspend_vet' => 'suspend_vet',
    'get_pending_vets' => 'get_pending_vets',
];

if (isset($handlers[$action])) {
    call_user_func($handlers[$action]);
} else {
    json_response(['error' => 'Unknown action'];
};

// ============================================
function get_pending_vets(): void {
    $stmt = db()->query(
        "SELECT u.id, u.name, u.phone, u.wilaya, u.created_at,
                vp.license_no, vp.verification_status, vp.submitted_at,
                COUNT(vd.id) as doc_count
         FROM baitari_users u
         JOIN baitari_vet_profiles vp ON vp.vet_id = u.id
         LEFT JOIN baitari_vet_documents vd ON vd.vet_id = u.id
         WHERE u.role = 'vet'
           AND vp.verification_status IN ('docs_submitted','under_review','pending_docs')
         GROUP BY u.id
         ORDER BY vp.submitted_at DESC
         LIMIT 50"
    );
    json_response(['vets' => $stmt->fetchAll()]);
}

// ============================================
function get_vet_details(): void {
    $vet_id = sanitize_int($_GET['vet_id'] ?? 0);
    if (!$vet_id) json_response(['error' => 'vet_id required'], 422);

    // Vet profile
    $stmt = db()->prepare(
        "SELECT u.id, u.name, u.phone, u.email, u.wilaya, u.commune, u.created_at,
                vp.license_no, vp.verification_status, vp.submitted_at,
                vp.rejection_reason, vp.specialities, vp.bio, vp.experience_years
         FROM baitari_users u
         JOIN baitari_vet_profiles vp ON vp.vet_id = u.id
         WHERE u.id = :uid AND u.role = 'vet'"
    );
    $stmt->execute([':uid' => $vet_id]);
    $vet = $stmt->fetch();
    if (!$vet) json_response(['error' => 'الطبيب غير موجود'], 404);

    // Documents
    $docs = db()->prepare(
        "SELECT id, doc_type, doc_label, file_path, file_name, file_size, mime_type, uploaded_at
         FROM baitari_vet_documents WHERE vet_id = :uid ORDER BY uploaded_at DESC"
    );
    $docs->execute([':uid' => $vet_id]);

    json_response(['vet' => $vet, 'documents' => $docs->fetchAll()]);
}

// ============================================
function approve_vet(): void {
    $vet_id = sanitize_int($_POST['vet_id'] ?? 0);
    if (!$vet_id) json_response(['error' => 'vet_id required'], 422);

    $admin = current_user();

    // Update status
    db()->prepare(
        "UPDATE baitari_vet_profiles
         SET verification_status = 'approved',
             is_verified = 1,
             reviewed_by = :admin,
             reviewed_at = NOW()
         WHERE vet_id = :uid"
    )->execute([':admin' => $admin['id'], ':uid' => $vet_id]);

    // Notify vet
    db()->prepare(
        "INSERT INTO baitari_notifications (user_id, type, title, body)
         VALUES (:uid, 'system', '🎉 تم اعتماد حسابك!',
         'مرحباً بك في منصة بيطري! يمكنك الآن استقبال المواعيد والظهور في نتائج البحث.')"
    )->execute([':uid' => $vet_id]);

    json_response(['success' => true, 'message' => 'تم اعتماد الطبيب']);
}

// ============================================
function reject_vet(): void {
    $vet_id = sanitize_int($_POST['vet_id'] ?? 0);
    $reason = sanitize_str($_POST['reason'] ?? '', 500);
    if (!$vet_id) json_response(['error' => 'vet_id required'], 422);
    if (!$reason) json_response(['error' => 'سبب الرفض مطلوب'], 422);

    $admin = current_user();

    db()->prepare(
        "UPDATE baitari_vet_profiles
         SET verification_status = 'rejected',
             is_verified = 0,
             rejection_reason = :reason,
             reviewed_by = :admin,
             reviewed_at = NOW()
         WHERE vet_id = :uid"
    )->execute([':reason' => $reason, ':admin' => $admin['id'], ':uid' => $vet_id]);

    // Notify vet
    db()->prepare(
        "INSERT INTO baitari_notifications (user_id, type, title, body)
         VALUES (:uid, 'system', '⚠️ تم رفض طلبك', :body)"
    )->execute([
        ':uid'  => $vet_id,
        ':body' => "للأسف تم رفض طلب الاعتماد. السبب: {$reason} — يمكنك إعادة رفع الوثائق والمحاولة مجدداً.",
    ]);

    json_response(['success' => true, 'message' => 'تم رفض الطلب وإشعار الطبيب']);
}

// ============================================
function suspend_vet(): void {
    $vet_id = sanitize_int($_POST['vet_id'] ?? 0);
    $reason = sanitize_str($_POST['reason'] ?? '', 500);
    if (!$vet_id) json_response(['error' => 'vet_id required'], 422);

    db()->prepare(
        "UPDATE baitari_vet_profiles
         SET verification_status = 'suspended', is_verified = 0
         WHERE vet_id = :uid"
    )->execute([':uid' => $vet_id]);

    db()->prepare("UPDATE baitari_users SET is_active = 0 WHERE id = :uid")
       ->execute([':uid' => $vet_id]);

    json_response(['success' => true]);
}
