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

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

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

match ($action) {
    'save_clinic' => save_clinic($uid),
    'get_clinic'  => get_clinic($uid),
    default       => json_response(['error' => 'Unknown action'], 400),
};

// ============================================
function save_clinic(int $uid): void {
    $clinic_name  = sanitize_str($_POST['clinic_name']  ?? '');
    $clinic_addr  = sanitize_str($_POST['clinic_address'] ?? '', 500);
    $lat          = (float)($_POST['clinic_lat'] ?? 0);
    $lng          = (float)($_POST['clinic_lng'] ?? 0);
    $bio          = sanitize_str($_POST['bio'] ?? '', 1000);
    $exp          = (int)($_POST['experience_years'] ?? 0);
    $fee_clinic   = (float)($_POST['fee_clinic'] ?? 0);
    $fee_home     = (float)($_POST['fee_home'] ?? 0);
    $home_visits  = (int)($_POST['home_visits'] ?? 0);
    $emg          = (int)($_POST['accepts_emergency'] ?? 0);
    $tele         = (int)($_POST['teleconsult'] ?? 0);

    // Specialities: comma-separated → JSON array
    $specRaw  = sanitize_str($_POST['specialities'] ?? '');
    $specArr  = $specRaw ? array_filter(array_map('trim', explode(',', $specRaw))) : [];
    $specJson = json_encode(array_values($specArr));

    if (!$clinic_name) {
        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()) {
        $stmt = db()->prepare(
            "UPDATE baitari_vet_profiles SET
                clinic_name      = :cn,
                clinic_address   = :ca,
                clinic_lat       = :lat,
                clinic_lng       = :lng,
                bio              = :bio,
                experience_years = :exp,
                specialities     = :spec,
                fee_clinic       = :fc,
                fee_home         = :fh,
                home_visits      = :hv,
                accepts_emergency = :emg,
                teleconsult      = :tele
             WHERE vet_id = :uid"
        );
    } else {
        $stmt = db()->prepare(
            "INSERT INTO baitari_vet_profiles
             (vet_id, clinic_name, clinic_address, clinic_lat, clinic_lng,
              bio, experience_years, specialities, fee_clinic, fee_home,
              home_visits, accepts_emergency, teleconsult, license_no, verification_status)
             VALUES
             (:uid, :cn, :ca, :lat, :lng,
              :bio, :exp, :spec, :fc, :fh,
              :hv, :emg, :tele, 'PENDING', 'pending_docs')"
        );
    }

    $stmt->execute([
        ':uid'  => $uid,
        ':cn'   => $clinic_name,
        ':ca'   => $clinic_addr ?: null,
        ':lat'  => $lat ?: null,
        ':lng'  => $lng ?: null,
        ':bio'  => $bio ?: null,
        ':exp'  => $exp,
        ':spec' => $specJson,
        ':fc'   => $fee_clinic,
        ':fh'   => $fee_home,
        ':hv'   => $home_visits,
        ':emg'  => $emg,
        ':tele' => $tele,
    ]);

    json_response(['success' => true, 'message' => 'تم حفظ معلومات العيادة']);
}

// ============================================
function get_clinic(int $uid): void {
    $stmt = db()->prepare(
        "SELECT clinic_name, clinic_address, clinic_lat, clinic_lng,
                bio, experience_years, specialities,
                fee_clinic, fee_home, home_visits, accepts_emergency, teleconsult
         FROM baitari_vet_profiles WHERE vet_id = :uid"
    );
    $stmt->execute([':uid' => $uid]);
    $vp = $stmt->fetch();
    if ($vp && $vp['specialities']) {
        $vp['specialities'] = json_decode($vp['specialities'], true);
    }
    json_response(['clinic' => $vp ?: null]);
}
