<?php
require_once __DIR__ . '/../includes/config.php';

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: ' . APP_URL);

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

match ($action) {
    'search_vets'       => search_vets(),
    'emergency_request' => emergency_request(),
    'book_appointment'  => book_appointment(),
    'get_appointments'  => get_appointments(),
    'get_user_pets'     => get_user_pets(),
    'add_pet'           => add_pet(),
    'get_herd'          => get_herd(),
    default             => json_response(['error' => 'Unknown action'], 400),
};

// ============================================
// Search Veterinarians
// ============================================
function search_vets(): void {
    $lat    = (float)($_GET['lat'] ?? 36.75);
    $lng    = (float)($_GET['lng'] ?? 3.06);
    $query  = sanitize_str($_GET['q'] ?? '');
    $limit  = min(sanitize_int($_GET['limit'] ?? 10), 50);

    $sql = "SELECT u.id, u.name, u.avatar, u.wilaya, u.commune, u.lat, u.lng,
                   vp.specialities, vp.experience_years, vp.home_visits,
                   vp.fee_clinic, vp.fee_home, vp.rating, vp.review_count,
                   vp.is_available, vp.accepts_emergency, vp.clinic_name,
                   vp.bio
            FROM baitari_users u
            JOIN baitari_vet_profiles vp ON vp.vet_id = u.id
            WHERE u.role = 'vet' AND u.is_active = 1 AND vp.is_verified = 1";

    $params = [];
    if ($query) {
        $sql .= " AND (u.name LIKE :q OR vp.specialities LIKE :q2)";
        $params[':q'] = "%$query%";
        $params[':q2'] = "%$query%";
    }
    $sql .= " LIMIT $limit";

    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    $vets = $stmt->fetchAll();

    // Add calculated distance
    foreach ($vets as &$vet) {
        if ($vet['lat'] && $vet['lng']) {
            $vet['distance_km'] = round(haversine_km($lat, $lng, (float)$vet['lat'], (float)$vet['lng']), 1);
        } else {
            $vet['distance_km'] = null;
        }
        $vet['specialities'] = json_decode($vet['specialities'] ?? '[]', true);
    }

    // Sort by distance
    usort($vets, fn($a, $b) => ($a['distance_km'] ?? 999) <=> ($b['distance_km'] ?? 999));

    json_response(['vets' => $vets, 'count' => count($vets)]);
}

// ============================================
// Emergency Request
// ============================================
function emergency_request(): void {
    $user = require_login();
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        json_response(['error' => 'POST required'], 405);
    }

    $input       = json_decode(file_get_contents('php://input'), true) ?? $_POST;
    $animal_type = sanitize_str($input['animal_type'] ?? '');
    $problem     = sanitize_str($input['problem'] ?? '', 1000);
    $lat         = (float)($input['lat'] ?? 0);
    $lng         = (float)($input['lng'] ?? 0);
    $address     = sanitize_str($input['address'] ?? '', 300);

    if (!$animal_type || !$problem) {
        json_response(['error' => 'Missing required fields'], 422);
    }

    // Insert emergency
    $stmt = db()->prepare(
        "INSERT INTO baitari_emergencies (client_id, animal_type, problem, lat, lng, address)
         VALUES (:cid, :at, :prob, :lat, :lng, :addr)"
    );
    $stmt->execute([
        ':cid'  => $user['id'],
        ':at'   => $animal_type,
        ':prob' => $problem,
        ':lat'  => $lat ?: null,
        ':lng'  => $lng ?: null,
        ':addr' => $address ?: null,
    ]);
    $emergency_id = db()->lastInsertId();

    // Find nearest available emergency vet
    $nearest_vet = null;
    if ($lat && $lng) {
        $vstmt = db()->prepare(
            "SELECT u.id, u.name, u.phone, u.lat, u.lng
             FROM baitari_users u
             JOIN baitari_vet_profiles vp ON vp.vet_id = u.id
             WHERE u.role='vet' AND u.is_active=1 AND vp.is_verified=1
               AND vp.accepts_emergency=1 AND vp.is_available=1
               AND u.lat IS NOT NULL"
        );
        $vstmt->execute();
        $vets = $vstmt->fetchAll();

        $min_dist = PHP_FLOAT_MAX;
        foreach ($vets as $v) {
            $d = haversine_km($lat, $lng, (float)$v['lat'], (float)$v['lng']);
            if ($d < $min_dist) {
                $min_dist = $d;
                $nearest_vet = $v;
                $nearest_vet['distance_km'] = round($d, 1);
            }
        }
    }

    if ($nearest_vet) {
        db()->prepare("UPDATE baitari_emergencies SET status='assigned', assigned_vet=:vid, assigned_at=NOW() WHERE id=:eid")
           ->execute([':vid' => $nearest_vet['id'], ':eid' => $emergency_id]);

        // Insert notification for vet
        db()->prepare(
            "INSERT INTO baitari_notifications (user_id, type, title, body, data_json)
             VALUES (:uid, 'emergency', 'طلب طوارئ جديد', :body, :data)"
        )->execute([
            ':uid'  => $nearest_vet['id'],
            ':body' => "حيوان: $animal_type - المشكلة: $problem",
            ':data' => json_encode(['emergency_id' => $emergency_id]),
        ]);
    }

    json_response([
        'success'      => true,
        'emergency_id' => $emergency_id,
        'nearest_vet'  => $nearest_vet,
    ]);
}

// ============================================
// Book Appointment
// ============================================
function book_appointment(): void {
    $user = require_login();
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        json_response(['error' => 'POST required'], 405);
    }

    $input        = json_decode(file_get_contents('php://input'), true) ?? $_POST;
    $vet_id       = sanitize_int($input['vet_id'] ?? 0);
    $pet_id       = sanitize_int($input['pet_id'] ?? 0) ?: null;
    $herd_id      = sanitize_int($input['herd_id'] ?? 0) ?: null;
    $visit_type   = sanitize_str($input['visit_type'] ?? 'clinic');
    $scheduled_at = sanitize_str($input['scheduled_at'] ?? '');
    $symptoms     = sanitize_str($input['symptoms'] ?? '', 1000);
    $address      = sanitize_str($input['address'] ?? '', 300);

    if (!$vet_id || !$scheduled_at) {
        json_response(['error' => 'Missing required fields'], 422);
    }

    // Get vet fee
    $vp = db()->prepare("SELECT fee_clinic, fee_home FROM baitari_vet_profiles WHERE vet_id=:vid");
    $vp->execute([':vid' => $vet_id]);
    $fee_row = $vp->fetch();
    $fee = ($visit_type === 'home') ? ($fee_row['fee_home'] ?? 0) : ($fee_row['fee_clinic'] ?? 0);

    $stmt = db()->prepare(
        "INSERT INTO baitari_appointments
         (client_id, vet_id, pet_id, herd_id, visit_type, scheduled_at, symptoms, address, fee)
         VALUES (:cid, :vid, :pid, :hid, :vtype, :sat, :symp, :addr, :fee)"
    );
    $stmt->execute([
        ':cid'   => $user['id'],
        ':vid'   => $vet_id,
        ':pid'   => $pet_id,
        ':hid'   => $herd_id,
        ':vtype' => $visit_type,
        ':sat'   => $scheduled_at,
        ':symp'  => $symptoms ?: null,
        ':addr'  => $address ?: null,
        ':fee'   => $fee,
    ]);
    $appt_id = db()->lastInsertId();

    // Notify vet
    db()->prepare(
        "INSERT INTO baitari_notifications (user_id, type, title, body, data_json)
         VALUES (:uid, 'appointment', 'موعد جديد', :body, :data)"
    )->execute([
        ':uid'  => $vet_id,
        ':body' => "موعد جديد بتاريخ $scheduled_at",
        ':data' => json_encode(['appointment_id' => $appt_id]),
    ]);

    json_response(['success' => true, 'appointment_id' => $appt_id]);
}

// ============================================
// Get Appointments
// ============================================
function get_appointments(): void {
    $user   = require_login();
    $status = sanitize_str($_GET['status'] ?? '');
    $type   = sanitize_str($_GET['type'] ?? 'upcoming');

    $where  = $user['role'] === 'vet' ? 'a.vet_id = :uid' : 'a.client_id = :uid';
    $date_cond = $type === 'past'
        ? 'AND a.scheduled_at < NOW()'
        : 'AND a.scheduled_at >= NOW()';

    $sql = "SELECT a.*, 
                   u.name as other_name, u.phone as other_phone, u.avatar as other_avatar,
                   p.name as pet_name, p.species as pet_species, p.photo as pet_photo
            FROM baitari_appointments a
            JOIN baitari_users u ON u.id = " . ($user['role'] === 'vet' ? 'a.client_id' : 'a.vet_id') . "
            LEFT JOIN baitari_pets p ON p.id = a.pet_id
            WHERE $where $date_cond";

    if ($status) {
        $sql .= " AND a.status = :status";
    }
    $sql .= " ORDER BY a.scheduled_at " . ($type === 'past' ? 'DESC' : 'ASC') . " LIMIT 20";

    $stmt = db()->prepare($sql);
    $params = [':uid' => $user['id']];
    if ($status) $params[':status'] = $status;
    $stmt->execute($params);

    json_response(['appointments' => $stmt->fetchAll()]);
}

// ============================================
// Get User Pets
// ============================================
function get_user_pets(): void {
    $user = require_login();
    $stmt = db()->prepare("SELECT * FROM baitari_pets WHERE owner_id=:uid AND is_active=1 ORDER BY name");
    $stmt->execute([':uid' => $user['id']]);
    json_response(['pets' => $stmt->fetchAll()]);
}

// ============================================
// Add Pet
// ============================================
function add_pet(): void {
    $user = require_login();
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        json_response(['error' => 'POST required'], 405);
    }
    $input = json_decode(file_get_contents('php://input'), true) ?? $_POST;

    $stmt = db()->prepare(
        "INSERT INTO baitari_pets (owner_id, name, species, breed, gender, birth_date, weight_kg, notes)
         VALUES (:oid, :name, :sp, :br, :gen, :bd, :wt, :notes)"
    );
    $stmt->execute([
        ':oid'   => $user['id'],
        ':name'  => sanitize_str($input['name'] ?? ''),
        ':sp'    => sanitize_str($input['species'] ?? 'other'),
        ':br'    => sanitize_str($input['breed'] ?? ''),
        ':gen'   => sanitize_str($input['gender'] ?? 'unknown'),
        ':bd'    => $input['birth_date'] ?? null,
        ':wt'    => (float)($input['weight_kg'] ?? 0) ?: null,
        ':notes' => sanitize_str($input['notes'] ?? '', 500),
    ]);

    json_response(['success' => true, 'pet_id' => db()->lastInsertId()]);
}

// ============================================
// Get Farm Herd
// ============================================
function get_herd(): void {
    $user = require_login();
    $stmt = db()->prepare("SELECT * FROM baitari_herds WHERE farm_id=:uid ORDER BY species");
    $stmt->execute([':uid' => $user['id']]);
    json_response(['herds' => $stmt->fetchAll()]);
}
