<?php
ob_start();
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'] ?? '');

// Router - compatible with PHP 7.x and 8.x
$handlers = [
    'search_vets'        => 'search_vets',
    'emergency_request'  => 'emergency_request',
    'book_appointment'   => 'book_appointment',
    'book'               => 'book_appointment',
    'get_appointments'   => 'get_appointments',
    'update_profile'     => 'update_profile',
    'get_pets'           => 'get_pets_list',
    'get_user_pets'      => 'get_user_pets',
    'get_vets'           => 'get_vets_list',
    'debug_vets'         => 'debug_vets',
    'get_herds'          => 'get_herds_list',
    'add_pet'            => 'add_pet',
    'get_herd'           => 'get_herd',
    'update_appointment' => 'update_appointment',
    'save_report'        => 'save_report',
    'resolve_emergency'  => 'resolve_emergency',
    'add_herd'           => 'add_herd',
    'update_herd'        => 'update_herd',
];

if (isset($handlers[$action])) {
    call_user_func($handlers[$action]);
} else {
    json_response(['error' => 'Unknown action: ' . $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 book_appointment(): void {
    $user = require_login();
    $vet_id    = (int)($_POST['vet_id']    ?? 0);
    $pet_id    = (int)($_POST['pet_id']    ?? 0);
    $date      = sanitize_str($_POST['date']      ?? '');
    $time      = sanitize_str($_POST['time']      ?? '');
    $type      = sanitize_str($_POST['visit_type'] ?? 'clinic');
    $notes     = sanitize_str($_POST['notes']     ?? '', 500);

    if (!$vet_id || !$date) {
        json_response(['error' => 'بيانات ناقصة'], 422);
    }

    try {
        $scheduledAt = $date . ' ' . ($time ?: '09:00') . ':00';
    $stmt = db()->prepare(
            "INSERT INTO baitari_appointments
             (client_id, vet_id, pet_id, visit_type, scheduled_at, status, symptoms)
             VALUES (:cid, :vid, :pid, :type, :sat, 'pending', :notes)"
        );
        $stmt->execute([
            ':cid'   => $user['id'],
            ':vid'   => $vet_id,
            ':pid'   => $pet_id ?: null,
            ':type'  => in_array($type,['clinic','home','emergency','teleconsult']) ? $type : 'clinic',
            ':sat'   => $scheduledAt,
            ':notes' => $notes,
        ]);
        json_response(['success' => true, 'appt_id' => db()->lastInsertId()]);
    } catch(Exception $e) {
        json_response(['error' => 'خطأ في الحجز: ' . $e->getMessage()], 500);
    }
}

function update_profile(): void {
    $user = require_login();
    $name = sanitize_str($_POST['name'] ?? '', 80);
    if (!$name) json_response(['error' => 'الاسم مطلوب'], 422);
    db()->prepare("UPDATE baitari_users SET name=:n WHERE id=:id")
       ->execute([':n' => $name, ':id' => $user['id']]);
    json_response(['success' => true]);
}

function get_pets_list(): void {
    $user = require_login();
    try {
        $stmt = db()->prepare(
            "SELECT id, name, species, breed, birth_date, weight_kg, is_vaccinated
             FROM baitari_pets WHERE owner_id = :uid ORDER BY created_at DESC"
        );
        $stmt->execute([':uid' => $user['id']]);
        $pets = $stmt->fetchAll(PDO::FETCH_ASSOC);
        json_response(['success' => true, 'pets' => $pets ?: []]);
    } catch(Exception $e) {
        json_response(['success' => true, 'pets' => []]);
    }
}

function debug_vets(): void {
    try {
        // Test 1: count vets
        $s1 = db()->query("SELECT COUNT(*) as cnt FROM baitari_users WHERE role='vet'");
        $vet_count = $s1->fetch()['cnt'];
        
        // Test 2: count vet profiles
        $s2 = db()->query("SELECT COUNT(*) as cnt FROM baitari_vet_profiles WHERE is_verified=1");
        $profile_count = $s2->fetch()['cnt'];
        
        // Test 3: try the actual join
        $s3 = db()->query("SELECT u.id, u.name, vp.is_verified FROM baitari_users u 
                          JOIN baitari_vet_profiles vp ON vp.vet_id = u.id 
                          WHERE u.role='vet' LIMIT 3");
        $joined = $s3->fetchAll(PDO::FETCH_ASSOC);
        
        // Test 4: check review_count column exists
        $s4 = db()->query("SHOW COLUMNS FROM baitari_vet_profiles LIKE 'review_count'");
        $has_review_count = $s4->rowCount() > 0;
        
        json_response([
            'vet_users'     => (int)$vet_count,
            'vet_profiles'  => (int)$profile_count,
            'joined_sample' => $joined,
            'has_review_count' => $has_review_count,
        ]);
    } catch(Exception $e) {
        json_response(['error' => $e->getMessage()]);
    }
}

function get_vets_list(): void {
    try {
        // Safe query - only uses columns guaranteed to exist
        $stmt = db()->prepare(
            "SELECT u.id, u.name, u.wilaya, u.address,
                    vp.is_available, vp.home_visits,
                    vp.fee_clinic, vp.accepts_emergency,
                    vp.clinic_name, vp.rating
             FROM baitari_users u
             INNER JOIN baitari_vet_profiles vp ON vp.vet_id = u.id
             WHERE u.role = 'vet' AND u.is_active = 1
             ORDER BY vp.is_available DESC, vp.rating DESC
             LIMIT 20"
        );
        $stmt->execute();
        $vets = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Fallback: no profiles → return users directly
        if (empty($vets)) {
            $stmt2 = db()->prepare(
                "SELECT id, name, wilaya, address,
                        1 as is_available, 1 as home_visits,
                        0 as fee_clinic, 1 as accepts_emergency,
                        NULL as clinic_name, 5.0 as rating
                 FROM baitari_users
                 WHERE role = 'vet' AND is_active = 1
                 ORDER BY name LIMIT 20"
            );
            $stmt2->execute();
            $vets = $stmt2->fetchAll(PDO::FETCH_ASSOC);
        }

        foreach ($vets as &$v) {
            $v['specialty'] = 'طب بيطري عام';
            $v['rating']    = number_format((float)($v['rating'] ?? 5), 1);
            $v['reviews']   = 0;
        }

        json_response(['success' => true, 'vets' => $vets, 'count' => count($vets)]);
    } catch (Exception $e) {
        // Return error for debugging
        json_response(['success' => false, 'vets' => [], 'error' => $e->getMessage()]);
    }
}

function get_herds_list(): void {
    $user = require_login();
    try {
        $stmt = db()->prepare("SELECT * FROM baitari_herds WHERE owner_id = :uid ORDER BY created_at DESC LIMIT 10");
        $stmt->execute([':uid' => $user['id']]);
        $herds = $stmt->fetchAll(PDO::FETCH_ASSOC);
        json_response(['success' => true, 'herds' => $herds ?: []]);
    } catch(Exception $e) {
        json_response(['success' => true, 'herds' => []]);
    }
}

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;

    $name = sanitize_str($input['name'] ?? '');
    if (!$name) json_response(['error' => 'اسم الحيوان مطلوب'], 422);

    $stmt = db()->prepare(
        "INSERT INTO baitari_pets
         (owner_id, name, species, breed, gender, birth_date, weight_kg, is_vaccinated, notes)
         VALUES (:oid, :name, :sp, :br, :gen, :bd, :wt, :vacc, :notes)"
    );
    $stmt->execute([
        ':oid'   => $user['id'],
        ':name'  => $name,
        ':sp'    => sanitize_str($input['species'] ?? 'other'),
        ':br'    => sanitize_str($input['breed']   ?? ''),
        ':gen'   => sanitize_str($input['gender']  ?? 'unknown'),
        ':bd'    => !empty($input['birth_date']) ? $input['birth_date'] : null,
        ':wt'    => (float)($input['weight_kg']  ?? 0) ?: null,
        ':vacc'  => (int)($input['is_vaccinated'] ?? 0),
        ':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()]);
}

// ── Add to match statement ──
// 'update_appointment' => update_appointment(),
// 'save_report'        => save_report(),
// 'resolve_emergency'  => resolve_emergency(),
// 'add_herd'           => add_herd(),
// 'update_herd'        => update_herd(),
// 'set_availability'   => handled in vet_clinic.php


// ============================================
// UPDATE APPOINTMENT STATUS
// ============================================
function update_appointment(): void {
    $user   = require_login();
    $appt_id = sanitize_int($_POST['appt_id'] ?? 0);
    $status  = sanitize_str($_POST['status'] ?? '');
    $allowed = ['confirmed','rejected','in_progress','completed','cancelled'];
    if (!$appt_id || !in_array($status, $allowed)) {
        json_response(['error' => 'Invalid params'], 422);
    }
    // Verify ownership
    $col = $user['role'] === 'vet' ? 'vet_id' : 'client_id';
    db()->prepare("UPDATE baitari_appointments SET status=:s, updated_at=NOW() WHERE id=:id AND {$col}=:uid")
       ->execute([':s'=>$status,':id'=>$appt_id,':uid'=>$user['id']]);
    json_response(['success' => true]);
}

// ============================================
// SAVE MEDICAL REPORT
// ============================================
function save_report(): void {
    $user    = require_role('vet');
    $appt_id = sanitize_int($_POST['appt_id'] ?? 0);
    if (!$appt_id) json_response(['error' => 'appt_id required'], 422);

    // Get appointment
    $appt = db()->prepare("SELECT * FROM baitari_appointments WHERE id=:id AND vet_id=:uid");
    $appt->execute([':id'=>$appt_id,':uid'=>$user['id']]);
    $a = $appt->fetch();
    if (!$a) json_response(['error' => 'Not found'], 404);

    $status = sanitize_str($_POST['status'] ?? 'completed');

    // Insert medical record
    db()->prepare(
        "INSERT INTO baitari_medical_records
         (appt_id, pet_id, herd_id, vet_id, record_date, visit_reason, diagnosis, treatment, prescription, next_visit)
         VALUES (:aid,:pid,:hid,:vid,CURDATE(),:reason,:diag,:treat,:presc,:next)"
    )->execute([
        ':aid'    => $appt_id,
        ':pid'    => $a['pet_id'],
        ':hid'    => $a['herd_id'],
        ':vid'    => $user['id'],
        ':reason' => sanitize_str($_POST['visit_reason'] ?? $a['symptoms'] ?? '', 500),
        ':diag'   => sanitize_str($_POST['diagnosis']  ?? '', 1000),
        ':treat'  => sanitize_str($_POST['treatment']  ?? '', 1000),
        ':presc'  => sanitize_str($_POST['prescription']?? '', 1000),
        ':next'   => $_POST['next_visit'] ?: null,
    ]);

    // Update appointment status
    db()->prepare("UPDATE baitari_appointments SET status=:s, diagnosis=:d, prescription=:p WHERE id=:id")
       ->execute([':s'=>$status,':d'=>sanitize_str($_POST['diagnosis']??'',1000),':p'=>sanitize_str($_POST['prescription']??'',1000),':id'=>$appt_id]);

    // Notify client
    db()->prepare(
        "INSERT INTO baitari_notifications (user_id,type,title,body,data_json) VALUES (:uid,'appointment','تقرير طبي جديد',:body,:data)"
    )->execute([
        ':uid'  => $a['client_id'],
        ':body' => 'تم كتابة التقرير الطبي لزيارة '.date('d/m/Y'),
        ':data' => json_encode(['appt_id'=>$appt_id]),
    ]);

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

// ============================================
// RESOLVE EMERGENCY
// ============================================
function resolve_emergency(): void {
    $user   = require_role('vet');
    $emg_id = sanitize_int($_POST['emg_id'] ?? 0);
    if (!$emg_id) json_response(['error' => 'emg_id required'], 422);
    db()->prepare("UPDATE baitari_emergencies SET status='resolved', resolved_at=NOW() WHERE id=:id AND assigned_vet=:vid")
       ->execute([':id'=>$emg_id,':vid'=>$user['id']]);
    json_response(['success' => true]);
}

// ============================================
// ADD HERD
// ============================================
function add_herd(): void {
    $user = require_role('client');
    $stmt = db()->prepare(
        "INSERT INTO baitari_herds (farm_id, species, name, count, health_status, location_name, notes)
         VALUES (:fid,:sp,:name,:cnt,:hs,:loc,:notes)"
    );
    $stmt->execute([
        ':fid'   => $user['id'],
        ':sp'    => sanitize_str($_POST['species']       ?? 'other'),
        ':name'  => sanitize_str($_POST['name']          ?? ''),
        ':cnt'   => (int)($_POST['count']                ?? 0),
        ':hs'    => sanitize_str($_POST['health_status'] ?? 'healthy'),
        ':loc'   => sanitize_str($_POST['location_name'] ?? ''),
        ':notes' => sanitize_str($_POST['notes']         ?? '', 500),
    ]);
    json_response(['success' => true, 'herd_id' => db()->lastInsertId()]);
}

// ============================================
// UPDATE HERD
// ============================================
function update_herd(): void {
    $user    = require_role('client');
    $herd_id = sanitize_int($_POST['herd_id'] ?? 0);
    if (!$herd_id) json_response(['error' => 'herd_id required'], 422);
    db()->prepare(
        "UPDATE baitari_herds SET species=:sp, name=:name, count=:cnt,
         health_status=:hs, location_name=:loc, notes=:notes, updated_at=NOW()
         WHERE id=:id AND farm_id=:fid"
    )->execute([
        ':sp'    => sanitize_str($_POST['species']       ?? 'other'),
        ':name'  => sanitize_str($_POST['name']          ?? ''),
        ':cnt'   => (int)($_POST['count']                ?? 0),
        ':hs'    => sanitize_str($_POST['health_status'] ?? 'healthy'),
        ':loc'   => sanitize_str($_POST['location_name'] ?? ''),
        ':notes' => sanitize_str($_POST['notes']         ?? '', 500),
        ':id'    => $herd_id,
        ':fid'   => $user['id'],
    ]);
    json_response(['success' => true]);
}
