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

// Must be a vet
$user = current_user();
if (!$user || $user['role'] !== 'vet') {
    json_response(['error' => 'Unauthorized'], 401);
}
$uid = (int)$user['id'];

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

match ($action) {
    'upload_doc'    => upload_doc($uid),
    'delete_doc'    => delete_doc($uid),
    'save_license'  => save_license($uid),
    'submit_review' => submit_review($uid),
    default         => json_response(['error' => 'Unknown action'], 400),
};

// ============================================
// UPLOAD DOCUMENT
// ============================================
function upload_doc(int $uid): void {
    $doc_type = sanitize_str($_POST['doc_type'] ?? '');
    $allowed_types = ['national_id','diploma','license','professional_card','other'];

    if (!in_array($doc_type, $allowed_types)) {
        json_response(['error' => 'نوع الوثيقة غير صحيح'], 422);
    }

    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        json_response(['error' => 'لم يتم استلام الملف'], 422);
    }

    $file     = $_FILES['file'];
    $max_size = 5 * 1024 * 1024; // 5MB

    if ($file['size'] > $max_size) {
        json_response(['error' => 'حجم الملف يتجاوز 5MB'], 422);
    }

    // Validate MIME type
    $finfo     = finfo_open(FILEINFO_MIME_TYPE);
    $mime      = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    $allowed_mime = ['application/pdf','image/jpeg','image/png','image/webp'];

    if (!in_array($mime, $allowed_mime)) {
        json_response(['error' => 'نوع الملف غير مدعوم'], 422);
    }

    // Build upload path
    $ext       = match($mime) {
        'application/pdf' => 'pdf',
        'image/jpeg'      => 'jpg',
        'image/png'       => 'png',
        'image/webp'      => 'webp',
        default           => 'bin',
    };
    $dir       = UPLOAD_PATH . 'vet_docs/' . $uid . '/';
    if (!is_dir($dir)) mkdir($dir, 0755, true);

    $filename  = $doc_type . '_' . time() . '.' . $ext;
    $dest      = $dir . $filename;
    $rel_path  = $uid . '/' . $filename;

    if (!move_uploaded_file($file['tmp_name'], $dest)) {
        json_response(['error' => 'فشل في حفظ الملف'], 500);
    }

    // Delete previous doc of same type if exists
    $old = db()->prepare(
        "SELECT id, file_path FROM baitari_vet_documents
         WHERE vet_id = :uid AND doc_type = :type LIMIT 1"
    );
    $old->execute([':uid' => $uid, ':type' => $doc_type]);
    $oldDoc = $old->fetch();
    if ($oldDoc) {
        $oldPath = UPLOAD_PATH . 'vet_docs/' . $oldDoc['file_path'];
        if (file_exists($oldPath)) @unlink($oldPath);
        db()->prepare("DELETE FROM baitari_vet_documents WHERE id = :id")
           ->execute([':id' => $oldDoc['id']]);
    }

    // Insert new record
    $stmt = db()->prepare(
        "INSERT INTO baitari_vet_documents
         (vet_id, doc_type, doc_label, file_path, file_name, file_size, mime_type)
         VALUES (:uid, :type, :label, :path, :name, :size, :mime)"
    );
    $labels = [
        'national_id'       => 'بطاقة التعريف الوطنية',
        'diploma'           => 'شهادة الدكتوراه',
        'license'           => 'ترخيص مزاولة المهنة',
        'professional_card' => 'البطاقة المهنية',
        'other'             => 'وثيقة أخرى',
    ];
    $stmt->execute([
        ':uid'   => $uid,
        ':type'  => $doc_type,
        ':label' => $labels[$doc_type],
        ':path'  => $rel_path,
        ':name'  => basename($file['name']),
        ':size'  => $file['size'],
        ':mime'  => $mime,
    ]);
    $doc_id = db()->lastInsertId();

    // Fetch inserted doc
    $inserted = db()->prepare("SELECT * FROM baitari_vet_documents WHERE id = :id");
    $inserted->execute([':id' => $doc_id]);

    json_response(['success' => true, 'doc' => $inserted->fetch()]);
}

// ============================================
// DELETE DOCUMENT
// ============================================
function delete_doc(int $uid): void {
    $doc_id = sanitize_int($_POST['doc_id'] ?? 0);
    if (!$doc_id) json_response(['error' => 'معرّف الوثيقة مطلوب'], 422);

    // Must belong to this vet
    $doc = db()->prepare(
        "SELECT * FROM baitari_vet_documents WHERE id = :id AND vet_id = :uid"
    );
    $doc->execute([':id' => $doc_id, ':uid' => $uid]);
    $d = $doc->fetch();

    if (!$d) json_response(['error' => 'الوثيقة غير موجودة'], 404);

    // Delete file
    $path = UPLOAD_PATH . 'vet_docs/' . $d['file_path'];
    if (file_exists($path)) @unlink($path);

    // Delete record
    db()->prepare("DELETE FROM baitari_vet_documents WHERE id = :id")
       ->execute([':id' => $doc_id]);

    // Reset status back to pending_docs if was submitted
    db()->prepare(
        "UPDATE baitari_vet_profiles
         SET verification_status = 'pending_docs'
         WHERE vet_id = :uid AND verification_status IN ('docs_submitted','under_review')"
    )->execute([':uid' => $uid]);

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

// ============================================
// SAVE LICENSE NUMBER
// ============================================
function save_license(int $uid): void {
    $license = sanitize_str($_POST['license'] ?? '');
    if (!$license) json_response(['error' => 'رقم الترخيص مطلوب'], 422);

    // Upsert vet profile
    $exists = db()->prepare("SELECT id FROM baitari_vet_profiles WHERE vet_id = :uid");
    $exists->execute([':uid' => $uid]);

    if ($exists->fetch()) {
        db()->prepare("UPDATE baitari_vet_profiles SET license_no = :lic WHERE vet_id = :uid")
           ->execute([':lic' => $license, ':uid' => $uid]);
    } else {
        db()->prepare("INSERT INTO baitari_vet_profiles (vet_id, license_no) VALUES (:uid, :lic)")
           ->execute([':uid' => $uid, ':lic' => $license]);
    }

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

// ============================================
// SUBMIT FOR REVIEW
// ============================================
function submit_review(int $uid): void {
    $license = sanitize_str($_POST['license'] ?? '');

    // Check required docs uploaded
    $required = ['national_id', 'diploma', 'license'];
    $uploaded = db()->prepare(
        "SELECT doc_type FROM baitari_vet_documents WHERE vet_id = :uid"
    );
    $uploaded->execute([':uid' => $uid]);
    $uploadedTypes = array_column($uploaded->fetchAll(), 'doc_type');

    $missing = array_diff($required, $uploadedTypes);
    if (!empty($missing)) {
        $labels = [
            'national_id' => 'بطاقة التعريف',
            'diploma'     => 'شهادة الدكتوراه',
            'license'     => 'ترخيص مزاولة المهنة',
        ];
        $missingLabels = array_map(fn($k) => $labels[$k] ?? $k, $missing);
        json_response(['error' => 'الوثائق الناقصة: ' . implode('، ', $missingLabels)], 422);
    }

    if (!$license) {
        json_response(['error' => 'الرجاء إدخال رقم ترخيص مزاولة المهنة'], 422);
    }

    // Update profile
    db()->prepare(
        "UPDATE baitari_vet_profiles
         SET verification_status = 'docs_submitted',
             license_no = :lic,
             submitted_at = NOW()
         WHERE vet_id = :uid"
    )->execute([':lic' => $license, ':uid' => $uid]);

    // Notify admins
    $admins = db()->query(
        "SELECT id FROM baitari_users WHERE role = 'admin' AND is_active = 1"
    )->fetchAll();

    $vetName = db()->prepare("SELECT name FROM baitari_users WHERE id = :uid");
    $vetName->execute([':uid' => $uid]);
    $name = $vetName->fetchColumn();

    foreach ($admins as $admin) {
        db()->prepare(
            "INSERT INTO baitari_notifications (user_id, type, title, body, data_json)
             VALUES (:uid, 'system', 'طلب اعتماد طبيب جديد', :body, :data)"
        )->execute([
            ':uid'  => $admin['id'],
            ':body' => "الطبيب {$name} أرسل وثائقه للمراجعة",
            ':data' => json_encode(['vet_id' => $uid, 'action' => 'review_vet']),
        ]);
    }

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