<?php
// =========================================================
// ADMIN PANEL - COMPLETE WITH AFFILIATE MANAGEMENT
// =========================================================
session_start();
require_once '../../config.php';

// =========================================================
// LOGIN CHECK
// =========================================================
if (!isset($_SESSION['admin'])) {
    header('Location: login.php');
    exit;
}

// =========================================================
// HELPER FUNCTIONS (if not already defined)
// =========================================================
if (!function_exists('uploadImage')) {
    function uploadImage($file, $folder = 'uploads/') {
        if (!$file || $file['error'] != 0) return '';
        $targetDir = __DIR__ . '/' . $folder;
        if (!file_exists($targetDir)) mkdir($targetDir, 0755, true);
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) return '';
        $filename = time() . '_' . rand(1000, 9999) . '.' . $ext;
        if (move_uploaded_file($file['tmp_name'], $targetDir . $filename)) return $folder . $filename;
        return '';
    }
}
if (!function_exists('getYouTubeId')) {
    function getYouTubeId($url) {
        preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/)([^&]+)/', $url, $matches);
        return $matches[1] ?? '';
    }
}

// =========================================================
// AJAX HANDLERS
// =========================================================

// Appointment status update
if (isset($_POST['ajax_action']) && $_POST['ajax_action'] == 'update_appointment_status') {
    header('Content-Type: application/json');
    $app_id = (int)$_POST['appointment_id'];
    $action = $_POST['action'];
    $reason = $conn->real_escape_string($_POST['reason'] ?? '');
    $new_status = '';
    if ($action == 'approve') $new_status = 'confirmed';
    elseif ($action == 'complete') $new_status = 'completed';
    elseif ($action == 'cancel') $new_status = 'cancelled';
    if ($new_status) {
        $conn->query("UPDATE opd_appointments SET status='$new_status' WHERE id=$app_id");
        if ($action == 'approve') $conn->query("UPDATE opd_appointments SET approved_by=1, approved_at=NOW() WHERE id=$app_id");
        elseif ($action == 'cancel') $conn->query("UPDATE opd_appointments SET cancelled_at=NOW(), cancellation_reason='$reason' WHERE id=$app_id");
        if (function_exists('sendSMSViaBulkSMSBD')) {
            $app = $conn->query("SELECT patient_id FROM opd_appointments WHERE id=$app_id")->fetch_assoc();
            $patient = $conn->query("SELECT mobile FROM opd_patients WHERE id={$app['patient_id']}")->fetch_assoc();
            if ($patient) sendSMSViaBulkSMSBD($patient['mobile'], "Appointment #$app_id status changed to $new_status.");
        }
        echo json_encode(['success' => true, 'message' => "Appointment $action successful"]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit;
}

// Affiliate status update
if (isset($_POST['ajax_action']) && $_POST['ajax_action'] == 'update_affiliate_status') {
    header('Content-Type: application/json');
    $id = (int)$_POST['affiliate_id'];
    $status = $_POST['status'];
    $conn->query("UPDATE affiliates SET status = '$status' WHERE id = $id");
    echo json_encode(['success' => true, 'message' => 'Affiliate status updated']);
    exit;
}

// Update commission rate
if (isset($_POST['ajax_action']) && $_POST['ajax_action'] == 'update_commission') {
    header('Content-Type: application/json');
    $id = (int)$_POST['affiliate_id'];
    $rate = (float)$_POST['commission_rate'];
    $conn->query("UPDATE affiliates SET commission_rate = $rate WHERE id = $id");
    echo json_encode(['success' => true, 'message' => 'Commission rate updated']);
    exit;
}

// Appointment status update with SMS
if (isset($_POST['ajax_action']) && $_POST['ajax_action'] == 'update_appointment_status') {
    header('Content-Type: application/json');
    $app_id = (int)$_POST['appointment_id'];
    $action = $_POST['action'];
    $reason = $conn->real_escape_string($_POST['reason'] ?? '');
    $new_status = '';
    $status_text = '';
    
    if ($action == 'approve') {
        $new_status = 'confirmed';
        $status_text = 'নিশ্চিত করা হয়েছে';
    } elseif ($action == 'complete') {
        $new_status = 'completed';
        $status_text = 'সম্পন্ন হয়েছে';
    } elseif ($action == 'cancel') {
        $new_status = 'cancelled';
        $status_text = 'বাতিল করা হয়েছে';
    }
    
    if ($new_status) {
        $conn->query("UPDATE opd_appointments SET status='$new_status' WHERE id=$app_id");
        
        if ($action == 'approve') {
            $conn->query("UPDATE opd_appointments SET approved_by=1, approved_at=NOW() WHERE id=$app_id");
        } elseif ($action == 'cancel') {
            $conn->query("UPDATE opd_appointments SET cancelled_at=NOW(), cancellation_reason='$reason' WHERE id=$app_id");
        }
        
        // =========================================================
        // SEND SMS TO PATIENT ON STATUS CHANGE
        // =========================================================
      // =========================================================
// SEND SMS TO PATIENT ON STATUS CHANGE (Updated Template)
// =========================================================
$app = $conn->query("SELECT patient_id, appointment_date, fee, chamber_id, serial_no FROM opd_appointments WHERE id=$app_id")->fetch_assoc();
$patient = $conn->query("SELECT name, mobile FROM opd_patients WHERE id={$app['patient_id']}")->fetch_assoc();
$chamber = $conn->query("SELECT name, address, phone FROM chambers WHERE id={$app['chamber_id']}")->fetch_assoc();

if ($patient && function_exists('sendSMSViaBulkSMSBD')) {
    // Get time slot
    $time_slot = $conn->query("SELECT start_time FROM time_slots WHERE id = (SELECT time_slot_id FROM opd_appointments WHERE id=$app_id)")->fetch_assoc();
    $time = $time_slot ? date('h:i A', strtotime($time_slot['start_time'])) : '';
    
    // Format date
    $date_formatted = date('d/m/Y', strtotime($app['appointment_date']));
    $day_name = date('l', strtotime($app['appointment_date']));
    $bangla_days = ['Sunday' => 'রবিবার', 'Monday' => 'সোমবার', 'Tuesday' => 'মঙ্গলবার', 'Wednesday' => 'বুধবার', 'Thursday' => 'বৃহস্পতিবার', 'Friday' => 'শুক্রবার', 'Saturday' => 'শনিবার'];
    $day = $bangla_days[$day_name] ?? $day_name;
    
    // Chamber phone (if available, else use main number)
    $chamber_phone = !empty($chamber['phone']) ? $chamber['phone'] : '01775121112';
    
    if ($action == 'approve') {
        // =========================================================
        // APPROVAL SMS - CUSTOM TEMPLATE
        // =========================================================
        $msg = "Assalamualikum! আপনার সিরিয়াল নম্বর: {$app['serial_no']} তারিখ: $date_formatted ($day) সময়: $time চেম্বার: {$chamber['name']} হটলাইন: $chamber_phone ডা. মোঃ ফেরদৌস";
    } elseif ($action == 'complete') {
        $msg = "Assalamualikum! আপনার অ্যাপয়েন্টমেন্ট #$app_id সম্পন্ন হয়েছে। ধন্যবাদ - Dr. Ferdous";
    } elseif ($action == 'cancel') {
        $msg = "Assalamualikum! আপনার অ্যাপয়েন্টমেন্ট #$app_id বাতিল করা হয়েছে। কারণ: $reason বিস্তারিত জানতে যোগাযোগ করুন: 01775121112";
    }
    
    sendSMSViaBulkSMSBD($patient['mobile'], $msg);
}
        
        // =========================================================
        // SEND SMS TO ADMIN (Confirmation)
        // =========================================================
        $admin_phone = '01681519799'; // CHANGE TO YOUR ADMIN NUMBER
        $admin_msg = "✅ অ্যাপয়েন্টমেন্ট #$app_id $status_text\n"
                   . "রোগী: {$patient['name']}\n"
                   . "তারিখ: {$app['appointment_date']}";
        sendSMSViaBulkSMSBD($admin_phone, $admin_msg);
        
        echo json_encode(['success' => true, 'message' => "Appointment $action successful"]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit;
}

// Delete any record via AJAX
if (isset($_POST['ajax_action']) && $_POST['ajax_action'] == 'delete') {
    header('Content-Type: application/json');
    $table = $_POST['table'];
    $id = (int)$_POST['id'];
    $allowed = ['doctors', 'services', 'products', 'chambers', 'tutorials', 'blog_posts', 'blog_categories', 'site_banners', 'affiliates', 'affiliate_referrals', 'affiliate_payouts'];
    if (in_array($table, $allowed)) {
        $conn->query("DELETE FROM $table WHERE id=$id");
        echo json_encode(['success' => true, 'message' => 'Deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid table']);
    }
    exit;
}

// =========================================================
// NON-AJAX POST HANDLERS (for forms with file uploads)
// =========================================================
$msg = ''; $msgType = 'success';

// Brand
if (isset($_POST['save_brand'])) {
    $fields = ['name','slogan','about','phone','email','whatsapp','messenger','facebook','youtube','address'];
    foreach($fields as $f) { $v = $conn->real_escape_string($_POST[$f]??''); $conn->query("UPDATE brand SET `$f`='$v' WHERE id=1"); }
    if (isset($_FILES['logo']) && $_FILES['logo']['error']==0) { $lp = uploadImage($_FILES['logo']); if ($lp) $conn->query("UPDATE brand SET logo='$lp' WHERE id=1"); }
    if (isset($_FILES['hero_image']) && $_FILES['hero_image']['error']==0) { $hp = uploadImage($_FILES['hero_image']); if ($hp) $conn->query("UPDATE brand SET hero_image='$hp' WHERE id=1"); }
    $msg = "Brand updated!";
}

// Banners
if (isset($_POST['save_banner'])) {
    $title = $conn->real_escape_string($_POST['banner_title']??'');
    $subtitle = $conn->real_escape_string($_POST['banner_subtitle']??'');
    $bg = $conn->real_escape_string($_POST['banner_bg']??'#ff6b6b');
    $gradient = $conn->real_escape_string($_POST['banner_gradient']??'#ee5a24');
    $btn_text = $conn->real_escape_string($_POST['banner_btn_text']??'');
    $btn_link = $conn->real_escape_string($_POST['banner_btn_link']??'#');
    $anim = $conn->real_escape_string($_POST['banner_animation']??'slide');
    $icon = $conn->real_escape_string($_POST['banner_icon']??'fas fa-bullhorn');
    $active = isset($_POST['banner_active'])?1:0;
    $order = (int)($_POST['banner_order']??0);
    $conn->query("INSERT INTO site_banners (title, subtitle, bg_color, bg_gradient, button_text, button_link, animation, icon, is_active, display_order) VALUES ('$title','$subtitle','$bg','$gradient','$btn_text','$btn_link','$anim','$icon',$active,$order)");
    $msg = "Banner added!";
}

// Styles
if (isset($_POST['save_styles'])) {
    foreach($_POST as $key => $value) {
        if ($key != 'save_styles') {
            $v = $conn->real_escape_string($value);
            $conn->query("INSERT INTO site_styles (style_key, style_value) VALUES ('$key','$v') ON DUPLICATE KEY UPDATE style_value='$v'");
        }
    }
    $msg = "Styles updated!";
}

// Doctors
if (isset($_POST['save_doctor'])) {
    $id = (int)($_POST['doctor_id']??0);
    $name = $conn->real_escape_string($_POST['name']??'');
    $degree = $conn->real_escape_string($_POST['degree']??'');
    $spec = $conn->real_escape_string($_POST['specialization']??'');
    $exp = $conn->real_escape_string($_POST['experience']??'');
    $phone = $conn->real_escape_string($_POST['phone']??'');
    $wa = $conn->real_escape_string($_POST['whatsapp']??'');
    $chamber = $conn->real_escape_string($_POST['chamber']??'');
    $bio = $conn->real_escape_string($_POST['bio']??'');
    $active = isset($_POST['is_active'])?1:0;
    $order = (int)($_POST['display_order']??0);
    $photo = $_POST['existing_photo']??'';
    if (isset($_FILES['photo']) && $_FILES['photo']['error']==0) { $np = uploadImage($_FILES['photo']); if ($np) $photo = $np; }
    if ($id>0) $conn->query("UPDATE doctors SET name='$name', degree='$degree', specialization='$spec', experience='$exp', phone='$phone', whatsapp='$wa', chamber='$chamber', photo='$photo', bio='$bio', is_active=$active, display_order=$order WHERE id=$id");
    else $conn->query("INSERT INTO doctors (name, degree, specialization, experience, phone, whatsapp, chamber, photo, bio, is_active, display_order) VALUES ('$name','$degree','$spec','$exp','$phone','$wa','$chamber','$photo','$bio',$active,$order)");
    $msg = $id>0?"Doctor updated!":"Doctor added!";
}

// Services
if (isset($_POST['save_service'])) {
    $id = (int)($_POST['service_id']??0);
    $title = $conn->real_escape_string($_POST['title']??'');
    $desc = $conn->real_escape_string($_POST['description']??'');
    $icon = $conn->real_escape_string($_POST['icon']??'💊');
    $price = (float)($_POST['price']??0);
    $color = $conn->real_escape_string($_POST['color']??'#28a745');
    $anim = $conn->real_escape_string($_POST['animation']??'fade-up');
    $wmsg = $conn->real_escape_string($_POST['whatsapp_msg']??'');
    $active = isset($_POST['is_active'])?1:0;
    $order = (int)($_POST['display_order']??0);
    if ($id>0) $conn->query("UPDATE services SET title='$title', description='$desc', icon='$icon', price=$price, color='$color', animation='$anim', whatsapp_msg='$wmsg', is_active=$active, display_order=$order WHERE id=$id");
    else $conn->query("INSERT INTO services (title, description, icon, price, color, animation, whatsapp_msg, is_active, display_order) VALUES ('$title','$desc','$icon',$price,'$color','$anim','$wmsg',$active,$order)");
    $msg = $id>0?"Service updated!":"Service added!";
}

// Products
if (isset($_POST['save_product'])) {
    $id = (int)($_POST['product_id']??0);
    $name = $conn->real_escape_string($_POST['name']??'');
    $desc = $conn->real_escape_string($_POST['description']??'');
    $price = (float)($_POST['price']??0);
    $sale = (float)($_POST['sale_price']??0);
    $wmsg = $conn->real_escape_string($_POST['whatsapp_msg']??'');
    $color = $conn->real_escape_string($_POST['color']??'#007bff');
    $active = isset($_POST['is_active'])?1:0;
    $image = $_POST['existing_image']??'';
    if (isset($_FILES['image']) && $_FILES['image']['error']==0) { $ni = uploadImage($_FILES['image']); if ($ni) $image = $ni; }
    if ($id>0) $conn->query("UPDATE products SET name='$name', description='$desc', price=$price, sale_price=$sale, image='$image', whatsapp_msg='$wmsg', color='$color', is_active=$active WHERE id=$id");
    else $conn->query("INSERT INTO products (name, description, price, sale_price, image, whatsapp_msg, color, is_active) VALUES ('$name','$desc',$price,$sale,'$image','$wmsg','$color',$active)");
    $msg = $id>0?"Product updated!":"Product added!";
}

// Chambers
if (isset($_POST['save_chamber'])) {
    $id = (int)($_POST['chamber_id']??0);
    $name = $conn->real_escape_string($_POST['name']??'');
    $address = $conn->real_escape_string($_POST['address']??'');
    $city = $conn->real_escape_string($_POST['city']??'');
    $phone = $conn->real_escape_string($_POST['phone']??'');
    $schedule = $conn->real_escape_string($_POST['schedule']??'');
    $map = $conn->real_escape_string($_POST['map_link']??'');
    $active = isset($_POST['is_active'])?1:0;
    if ($id>0) $conn->query("UPDATE chambers SET name='$name', address='$address', city='$city', phone='$phone', schedule='$schedule', map_link='$map', is_active=$active WHERE id=$id");
    else $conn->query("INSERT INTO chambers (name, address, city, phone, schedule, map_link, is_active) VALUES ('$name','$address','$city','$phone','$schedule','$map',$active)");
    $msg = $id>0?"Chamber updated!":"Chamber added!";
}

// Tutorials
if (isset($_POST['save_tutorial'])) {
    $id = (int)($_POST['tutorial_id']??0);
    $title = $conn->real_escape_string($_POST['title']??'');
    $desc = $conn->real_escape_string($_POST['description']??'');
    $youtube_url = trim($_POST['youtube_url']??'');
    $category = $_POST['category']??'general';
    $duration = $conn->real_escape_string($_POST['duration']??'');
    $order = (int)($_POST['display_order']??0);
    $active = isset($_POST['is_active'])?1:0;
    $video_id = getYouTubeId($youtube_url);
    $thumbnail = "https://img.youtube.com/vi/{$video_id}/maxresdefault.jpg";
    if ($id>0) $conn->query("UPDATE tutorials SET title='$title', description='$desc', youtube_url='$youtube_url', video_id='$video_id', thumbnail='$thumbnail', category='$category', duration='$duration', display_order=$order, is_active=$active WHERE id=$id");
    else $conn->query("INSERT INTO tutorials (title, description, youtube_url, video_id, thumbnail, category, duration, display_order, is_active) VALUES ('$title','$desc','$youtube_url','$video_id','$thumbnail','$category','$duration',$order,$active)");
    $msg = $id>0?"Tutorial updated!":"Tutorial added!";
}

// Blog Category
if (isset($_POST['save_blog_category'])) {
    $id = (int)($_POST['category_id']??0);
    $name = $conn->real_escape_string($_POST['name']);
    $slug = $conn->real_escape_string($_POST['slug']??'');
    $desc = $conn->real_escape_string($_POST['description']??'');
    $order = (int)($_POST['display_order']??0);
    if ($id>0) $conn->query("UPDATE blog_categories SET name='$name', slug='$slug', description='$desc', display_order=$order WHERE id=$id");
    else $conn->query("INSERT INTO blog_categories (name, slug, description, display_order) VALUES ('$name','$slug','$desc',$order)");
    $msg = $id>0?"Category updated!":"Category added!";
}

// Blog Post
if (isset($_POST['save_blog_post'])) {
    $id = (int)($_POST['post_id']??0);
    $title = $conn->real_escape_string($_POST['title']);
    $slug = $conn->real_escape_string($_POST['slug']);
    $content = $conn->real_escape_string($_POST['content']);
    $excerpt = $conn->real_escape_string($_POST['excerpt']??'');
    $category_id = (int)$_POST['category_id'];
    $tags = $conn->real_escape_string($_POST['tags']??'');
    $status = $_POST['status']??'draft';
    $meta_title = $conn->real_escape_string($_POST['meta_title']??'');
    $meta_description = $conn->real_escape_string($_POST['meta_description']??'');
    $meta_keywords = $conn->real_escape_string($_POST['meta_keywords']??'');
    $image = $_POST['existing_image']??'';
    if (isset($_FILES['image']) && $_FILES['image']['error']==0) { $img = uploadImage($_FILES['image']); if ($img) $image = $img; }
    if ($id>0) {
        $conn->query("UPDATE blog_posts SET title='$title', slug='$slug', content='$content', excerpt='$excerpt', category_id=$category_id, tags='$tags', status='$status', image='$image', meta_title='$meta_title', meta_description='$meta_description', meta_keywords='$meta_keywords', updated_at=NOW() WHERE id=$id");
        $msg = "Post updated!";
    } else {
        $conn->query("INSERT INTO blog_posts (title, slug, content, excerpt, category_id, tags, status, image, meta_title, meta_description, meta_keywords) VALUES ('$title','$slug','$content','$excerpt',$category_id,'$tags','$status','$image','$meta_title','$meta_description','$meta_keywords')");
        $msg = "Post added!";
    }
}

// =========================================================
// DATA FETCHING
// =========================================================
$tab = $_GET['tab'] ?? 'dashboard';
$subtab = $_GET['subtab'] ?? 'list';
$brand = $conn->query("SELECT * FROM brand LIMIT 1")->fetch_assoc();

// All modules data
$doctors = $conn->query("SELECT * FROM doctors ORDER BY display_order");
$services = $conn->query("SELECT * FROM services ORDER BY display_order");
$products = $conn->query("SELECT * FROM products ORDER BY id DESC");
$chambers = $conn->query("SELECT * FROM chambers ORDER BY id");
$customers = $conn->query("SELECT * FROM customers ORDER BY id DESC LIMIT 100");
$banners = $conn->query("SELECT * FROM site_banners ORDER BY display_order");
$tutorials = $conn->query("SELECT * FROM tutorials ORDER BY category, display_order");
$blog_categories = $conn->query("SELECT * FROM blog_categories ORDER BY display_order");
$blog_posts = $conn->query("SELECT p.*, c.name as category_name FROM blog_posts p LEFT JOIN blog_categories c ON p.category_id = c.id ORDER BY p.created_at DESC");

// Affiliate data
$affiliates = $conn->query("SELECT * FROM affiliates ORDER BY id DESC");
$referrals = $conn->query("SELECT r.*, a.name as affiliate_name, a.email as affiliate_email, o.order_number, o.total_amount 
                           FROM affiliate_referrals r 
                           LEFT JOIN affiliates a ON r.affiliate_id = a.id 
                           LEFT JOIN orders o ON r.order_id = o.id 
                           ORDER BY r.created_at DESC LIMIT 100");
$payouts = $conn->query("SELECT p.*, a.name as affiliate_name, a.email as affiliate_email 
                         FROM affiliate_payouts p 
                         LEFT JOIN affiliates a ON p.affiliate_id = a.id 
                         ORDER BY p.requested_at DESC");

// Appointment stats
$total_appointments = $conn->query("SELECT COUNT(*) as total FROM opd_appointments")->fetch_assoc()['total'];
$pending_appointments = $conn->query("SELECT COUNT(*) as total FROM opd_appointments WHERE status='pending'")->fetch_assoc()['total'];
$confirmed_appointments = $conn->query("SELECT COUNT(*) as total FROM opd_appointments WHERE status='confirmed'")->fetch_assoc()['total'];
$completed_appointments = $conn->query("SELECT COUNT(*) as total FROM opd_appointments WHERE status='completed'")->fetch_assoc()['total'];
$cancelled_appointments = $conn->query("SELECT COUNT(*) as total FROM opd_appointments WHERE status='cancelled'")->fetch_assoc()['total'];

// Affiliate stats
$total_affiliates = $conn->query("SELECT COUNT(*) as count FROM affiliates")->fetch_assoc()['count'];
$active_affiliates = $conn->query("SELECT COUNT(*) as count FROM affiliates WHERE status = 'active'")->fetch_assoc()['count'];
$total_referrals_count = $conn->query("SELECT COUNT(*) as count FROM affiliate_referrals")->fetch_assoc()['count'];
$total_commission = $conn->query("SELECT SUM(commission_amount) as total FROM affiliate_referrals WHERE status IN ('approved','paid')")->fetch_assoc()['total'] ?? 0;
$pending_payouts = $conn->query("SELECT SUM(amount) as total FROM affiliate_payouts WHERE status = 'pending'")->fetch_assoc()['total'] ?? 0;

// Appointments filter
$status_filter = $_GET['status'] ?? '';
$chamber_filter = $_GET['chamber'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$where = "WHERE 1=1";
if ($status_filter) $where .= " AND a.status = '$status_filter'";
if ($chamber_filter) $where .= " AND a.chamber_id = " . intval($chamber_filter);
if ($date_from) $where .= " AND a.appointment_date >= '$date_from'";
if ($date_to) $where .= " AND a.appointment_date <= '$date_to'";
$appointments = $conn->query("SELECT a.*, p.name as patient_name, p.mobile as patient_mobile, c.name as chamber_name, ts.start_time, ts.end_time FROM opd_appointments a JOIN opd_patients p ON a.patient_id = p.id JOIN chambers c ON a.chamber_id = c.id LEFT JOIN time_slots ts ON a.time_slot_id = ts.id $where ORDER BY a.appointment_date DESC, ts.start_time ASC");

$total_doctors = $doctors->num_rows;
$total_services = $services->num_rows;
$total_products = $products->num_rows;
$total_customers = $customers->num_rows;
$total_posts = $blog_posts->num_rows;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Admin Panel | <?= htmlspecialchars($brand['name']) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        :root{--p:#2d6a4f;--pl:#52b788;--pd:#1b4332}
        *{font-family:'Segoe UI',sans-serif;box-sizing:border-box}
        body{background:#f0f2f5;overflow-x:hidden;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
        .sidebar{background:linear-gradient(180deg,#1b4332,#2d6a4f);min-height:100vh;color:#fff;position:fixed;width:250px;z-index:1000;overflow-y:auto;transition:transform 0.3s cubic-bezier(0.25,0.46,0.45,0.94)}
        .sidebar .brand{padding:20px;text-align:center;border-bottom:1px solid rgba(255,255,255,.1)}
        .sidebar a{color:rgba(255,255,255,.85);text-decoration:none;padding:11px 18px;display:block;margin:2px 10px;border-radius:10px;transition:all 0.2s;font-size:.9rem}
        .sidebar a:hover,.sidebar a.active{background:rgba(255,255,255,.15);color:#fff;transform:translateX(5px)}
        .sidebar a i{width:22px;margin-right:10px}
        .main-content{margin-left:250px;padding:20px;transition:margin 0.3s}
        .card{border:none;border-radius:15px;box-shadow:0 3px 15px rgba(0,0,0,.08);margin-bottom:20px;background:#fff;transition:transform 0.2s,box-shadow 0.2s}
        .card:hover{box-shadow:0 5px 20px rgba(0,0,0,.12)}
        .card-header{background:var(--p);color:#fff;border-radius:15px 15px 0 0!important;padding:14px 20px;font-weight:600}
        .stat-card{background:#fff;border-radius:15px;padding:20px;box-shadow:0 3px 15px rgba(0,0,0,.08);border-left:4px solid var(--p);transition:all 0.3s;cursor:pointer}
        .stat-card:hover{transform:translateY(-5px);box-shadow:0 10px 25px rgba(0,0,0,.1)}
        .stat-number{font-size:2rem;font-weight:800;color:var(--p)}
        .stat-label{color:#6c757d;font-size:.85rem}
        .stat-icon{font-size:2rem;opacity:.2;float:right}
        .btn-primary{background:var(--p);border:none;transition:all 0.2s}
        .btn-primary:hover{background:var(--pd);transform:translateY(-2px);box-shadow:0 4px 12px rgba(45,106,79,0.3)}
        .table th{background:#f8f9fa;font-weight:600;font-size:.85rem;white-space:nowrap}
        .table td{vertical-align:middle;font-size:.85rem}
        .form-section{background:#f8f9fa;border-radius:12px;padding:20px;margin-bottom:20px;border:1px solid #dee2e6}
        .preview-image{max-width:100px;max-height:100px;border-radius:10px;border:3px solid var(--pl);object-fit:cover}
        .status-badge{padding:4px 10px;border-radius:30px;font-size:12px;font-weight:600;display:inline-block}
        .status-pending{background:#ffc107;color:#000}
        .status-confirmed{background:#28a745;color:#fff}
        .status-completed{background:#17a2b8;color:#fff}
        .status-cancelled{background:#dc3545;color:#fff}
        .badge-active{background:#28a745;color:#fff}
        .badge-inactive{background:#6c757d;color:#fff}
        .badge-approved{background:#28a745;color:#fff}
        .badge-paid{background:#17a2b8;color:#fff}
        .menu-toggle{display:none;position:fixed;top:15px;left:15px;z-index:1001;background:var(--p);color:#fff;border:none;width:40px;height:40px;border-radius:50%;cursor:pointer}
        .menu-toggle:hover{transform:scale(1.05)}
        .toast-container{position:fixed;bottom:20px;right:20px;z-index:9999;display:flex;flex-direction:column;gap:8px;max-width:400px;width:100%}
        .toast-item{background:#fff;border-radius:12px;padding:12px 20px;box-shadow:0 10px 30px rgba(0,0,0,.15);display:flex;align-items:center;gap:12px;animation:slideIn 0.4s cubic-bezier(0.25,0.46,0.45,0.94);border-left:4px solid #28a745}
        .toast-item.danger{border-left-color:#dc3545}
        .toast-item.warning{border-left-color:#ffc107}
        .toast-item .close-btn{background:none;border:none;font-size:1.2rem;cursor:pointer;margin-left:auto;color:#999}
        .toast-item .close-btn:hover{transform:scale(1.2)}
        @keyframes slideIn{from{transform:translateX(100%);opacity:0}to{transform:translateX(0);opacity:1}}
        .btn-loading{cursor:wait;opacity:.7}
        .btn-loading .spinner{display:inline-block;animation:spin 1s linear infinite}
        @keyframes spin{to{transform:rotate(360deg)}}
        ::-webkit-scrollbar{width:8px;height:8px}
        ::-webkit-scrollbar-track{background:#f1f1f1}
        ::-webkit-scrollbar-thumb{background:var(--p);border-radius:10px}
        ::-webkit-scrollbar-thumb:hover{background:var(--pd)}
        @media(max-width:992px){.menu-toggle{display:block}.sidebar{transform:translateX(-100%);position:fixed}.sidebar.show{transform:translateX(0)}.main-content{margin-left:0;padding-top:60px}}
        @media(max-width:768px){.stat-number{font-size:1.5rem}.card-header{font-size:.9rem}.btn{font-size:.8rem;padding:6px 12px}.table th,.table td{font-size:.75rem;padding:6px}}
        .nav-pills .nav-link{color:#fff!important}
        .nav-pills .nav-link.active{background:rgba(255,255,255,0.25)!important;color:#fff!important}
    </style>
</head>
<body>
<button class="menu-toggle" id="menuToggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
<div class="d-flex">
    <div class="sidebar" id="sidebar">
        <div class="brand"><h6><i class="fas fa-hospital-user"></i> <?= htmlspecialchars($brand['name']) ?></h6><small>Admin v4.0</small></div>
        <div class="p-2">
            <a href="?tab=dashboard" class="<?=$tab=='dashboard'?'active':''?>"><i class="fas fa-th-large"></i> Dashboard</a>
            <a href="?tab=brand" class="<?=$tab=='brand'?'active':''?>"><i class="fas fa-building"></i> Brand</a>
            <a href="?tab=banners" class="<?=$tab=='banners'?'active':''?>"><i class="fas fa-ad"></i> Banners</a>
            <a href="?tab=styles" class="<?=$tab=='styles'?'active':''?>"><i class="fas fa-paint-brush"></i> Styles</a>
            <a href="?tab=doctors" class="<?=$tab=='doctors'?'active':''?>"><i class="fas fa-user-md"></i> Doctors</a>
            <a href="?tab=services" class="<?=$tab=='services'?'active':''?>"><i class="fas fa-list-alt"></i> Services</a>
            <a href="?tab=products" class="<?=$tab=='products'?'active':''?>"><i class="fas fa-box"></i> Products</a>
            <a href="?tab=chambers" class="<?=$tab=='chambers'?'active':''?>"><i class="fas fa-clinic-medical"></i> Chambers</a>
            <a href="?tab=tutorials" class="<?=$tab=='tutorials'?'active':''?>"><i class="fas fa-graduation-cap"></i> Tutorials</a>
            <a href="?tab=appointments" class="<?=$tab=='appointments'?'active':''?>"><i class="fas fa-calendar-check"></i> Appointments</a>
            <a href="?tab=blog" class="<?=$tab=='blog'?'active':''?>"><i class="fas fa-blog"></i> Blog</a>
            <a href="?tab=blog_categories" class="<?=$tab=='blog_categories'?'active':''?>"><i class="fas fa-tags"></i> Blog Cats</a>
            <a href="?tab=customers" class="<?=$tab=='customers'?'active':''?>"><i class="fas fa-users"></i> Customers</a>
            <a href="orders.php"><i class="fas fa-truck"></i> Orders</a>
            <a href="?tab=affiliates" class="<?=$tab=='affiliates'?'active':''?>"><i class="fas fa-handshake"></i> Affiliates</a>
            <hr>
            <a href="../index.php" target="_blank"><i class="fas fa-globe"></i> View Site</a>
            <!-- Add this to your website footer or sidebar -->
<div class="admin-access" style="text-align: center; padding: 10px; margin-top: 20px; border-top: 1px solid #ddd;">
    <a href="/opd/admin_config.php" style="color: #999; text-decoration: none; font-size: 12px;">
        🔒 Admin Access
    </a>
</div>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>

    <div class="main-content flex-grow-1">
        <?php if ($msg): ?>
            <div class="alert alert-<?=$msgType?> alert-dismissible fade show"><?=$msg?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>

        <!-- =========================================================
             DASHBOARD
             ========================================================= -->
        <?php if($tab=='dashboard'): ?>
        <div class="animated">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4><i class="fas fa-chart-line"></i> Dashboard</h4>
                <span><?=date('l, d M Y')?></span>
            </div>
            <div class="row g-3 mb-4">
                <div class="col-md-2 col-6"><div class="stat-card" onclick="location.href='?tab=appointments'"><div class="stat-number"><?=$total_appointments?></div><div class="stat-label">Total Apps</div><div class="stat-icon"><i class="fas fa-calendar"></i></div></div></div>
                <div class="col-md-2 col-6"><div class="stat-card" onclick="location.href='?tab=appointments&status=pending'"><div class="stat-number"><?=$pending_appointments?></div><div class="stat-label">Pending</div><div class="stat-icon"><i class="fas fa-clock"></i></div></div></div>
                <div class="col-md-2 col-6"><div class="stat-card" onclick="location.href='?tab=doctors'"><div class="stat-number"><?=$total_doctors?></div><div class="stat-label">Doctors</div><div class="stat-icon"><i class="fas fa-user-md"></i></div></div></div>
                <div class="col-md-2 col-6"><div class="stat-card" onclick="location.href='?tab=services'"><div class="stat-number"><?=$total_services?></div><div class="stat-label">Services</div><div class="stat-icon"><i class="fas fa-list-alt"></i></div></div></div>
                <div class="col-md-2 col-6"><div class="stat-card" onclick="location.href='?tab=products'"><div class="stat-number"><?=$total_products?></div><div class="stat-label">Products</div><div class="stat-icon"><i class="fas fa-box"></i></div></div></div>
                <div class="col-md-2 col-6"><div class="stat-card" onclick="location.href='?tab=blog'"><div class="stat-number"><?=$total_posts?></div><div class="stat-label">Blog Posts</div><div class="stat-icon"><i class="fas fa-newspaper"></i></div></div></div>
            </div>
            <div class="row g-3 mb-4">
                <div class="col-md-2 col-6"><div class="stat-card" style="border-left-color:#6f42c1" onclick="location.href='?tab=affiliates'"><div class="stat-number" style="color:#6f42c1"><?=$total_affiliates?></div><div class="stat-label">Affiliates</div><div class="stat-icon"><i class="fas fa-handshake"></i></div></div></div>
                <div class="col-md-2 col-6"><div class="stat-card" style="border-left-color:#28a745" onclick="location.href='?tab=affiliates'"><div class="stat-number" style="color:#28a745"><?=$active_affiliates?></div><div class="stat-label">Active</div><div class="stat-icon"><i class="fas fa-user-check"></i></div></div></div>
                <div class="col-md-2 col-6"><div class="stat-card" style="border-left-color:#17a2b8" onclick="location.href='?tab=affiliates&subtab=referrals'"><div class="stat-number" style="color:#17a2b8"><?=$total_referrals_count?></div><div class="stat-label">Referrals</div><div class="stat-icon"><i class="fas fa-link"></i></div></div></div>
                <div class="col-md-2 col-6"><div class="stat-card" style="border-left-color:#ffc107" onclick="location.href='?tab=affiliates&subtab=referrals'"><div class="stat-number" style="color:#ffc107">৳<?=number_format($total_commission,2)?></div><div class="stat-label">Commission</div><div class="stat-icon"><i class="fas fa-money-bill"></i></div></div></div>
                <div class="col-md-2 col-6"><div class="stat-card" style="border-left-color:#dc3545" onclick="location.href='?tab=affiliates&subtab=payouts'"><div class="stat-number" style="color:#dc3545">৳<?=number_format($pending_payouts,2)?></div><div class="stat-label">Pending Payouts</div><div class="stat-icon"><i class="fas fa-hourglass"></i></div></div></div>
            </div>
            <div class="card"><div class="card-header">Quick Actions</div><div class="card-body"><div class="row g-2"><div class="col-md-2 col-6"><a href="?tab=doctors" class="btn btn-primary w-100">Add Doctor</a></div><div class="col-md-2 col-6"><a href="?tab=services" class="btn btn-primary w-100">Add Service</a></div><div class="col-md-2 col-6"><a href="?tab=blog" class="btn btn-primary w-100">Write Post</a></div><div class="col-md-2 col-6"><a href="orders.php" class="btn btn-primary w-100">View Orders</a></div><div class="col-md-2 col-6"><a href="?tab=affiliates" class="btn btn-primary w-100">Affiliates</a></div><div class="col-md-2 col-6"><a href="?tab=affiliates&subtab=payouts" class="btn btn-primary w-100">Payouts</a></div></div></div></div>
        </div>
        <?php endif; ?>

        <!-- =========================================================
             BRAND
             ========================================================= -->
        <?php if($tab=='brand'): ?>
        <div class="card"><div class="card-header">Brand Settings</div><div class="card-body">
            <form method="POST" enctype="multipart/form-data"><div class="row">
                <div class="col-md-3 text-center"><label>Logo</label><br><?php if($brand['logo']):?><img src="<?=$brand['logo']?>" class="preview-image mb-2" id="logoPreview"><?php else:?><div class="preview-image bg-light d-flex align-items-center justify-content-center mx-auto mb-2">🏥</div><?php endif;?><input type="file" name="logo" class="form-control" accept="image/*" onchange="previewImage(this,'logoPreview')"></div>
                <div class="col-md-3 text-center"><label>Hero Image</label><br><?php if($brand['hero_image']):?><img src="<?=$brand['hero_image']?>" class="preview-image mb-2" id="heroPreview"><?php else:?><div class="preview-image bg-light d-flex align-items-center justify-content-center mx-auto mb-2">🖼️</div><?php endif;?><input type="file" name="hero_image" class="form-control" accept="image/*" onchange="previewImage(this,'heroPreview')"></div>
                <div class="col-md-6"><div class="mb-2"><label>Name</label><input type="text" name="name" class="form-control" value="<?=htmlspecialchars($brand['name'])?>" required></div><div class="mb-2"><label>Slogan</label><input type="text" name="slogan" class="form-control" value="<?=htmlspecialchars($brand['slogan'])?>"></div><div class="mb-2"><label>WhatsApp</label><input type="text" name="whatsapp" class="form-control" value="<?=$brand['whatsapp']?>"></div></div>
            </div><div class="row mt-3"><div class="col-md-4"><label>Phone</label><input type="text" name="phone" class="form-control" value="<?=$brand['phone']?>"></div><div class="col-md-4"><label>Email</label><input type="email" name="email" class="form-control" value="<?=$brand['email']?>"></div><div class="col-md-4"><label>Messenger</label><input type="text" name="messenger" class="form-control" value="<?=$brand['messenger']?>"></div>
            <div class="col-md-6"><label>Facebook</label><input type="text" name="facebook" class="form-control" value="<?=$brand['facebook']?>"></div><div class="col-md-6"><label>YouTube</label><input type="text" name="youtube" class="form-control" value="<?=$brand['youtube']?>"></div>
            <div class="col-12"><label>Address</label><textarea name="address" class="form-control" rows="2"><?=$brand['address']?></textarea></div><div class="col-12"><label>About</label><textarea name="about" class="form-control" rows="3"><?=$brand['about']?></textarea></div></div>
            <button type="submit" name="save_brand" class="btn btn-primary mt-3">Save</button></form>
        </div></div>
        <?php endif; ?>

        <!-- =========================================================
             BANNERS
             ========================================================= -->
        <?php if($tab=='banners'): ?>
        <div class="card"><div class="card-header d-flex justify-content-between"><span>Banners</span><button class="btn btn-light btn-sm" onclick="toggleForm('bannerForm')">+ New</button></div><div class="card-body">
            <div id="bannerForm" class="form-section" style="display:none"><form method="POST"><div class="row g-2"><div class="col-md-6"><input type="text" name="banner_title" placeholder="Title" class="form-control" required></div><div class="col-md-6"><input type="text" name="banner_subtitle" placeholder="Subtitle" class="form-control"></div><div class="col-md-3"><input type="color" name="banner_bg" value="#ff6b6b" class="form-control"></div><div class="col-md-3"><input type="color" name="banner_gradient" value="#ee5a24" class="form-control"></div><div class="col-md-3"><input type="text" name="banner_btn_text" placeholder="Button Text" class="form-control"></div><div class="col-md-3"><input type="text" name="banner_btn_link" placeholder="Link" class="form-control"></div><div class="col-md-4"><select name="banner_animation" class="form-select"><option>slide</option><option>fade</option><option>zoom</option></select></div><div class="col-md-4"><input type="text" name="banner_icon" placeholder="Icon class" class="form-control" value="fas fa-bullhorn"></div><div class="col-md-4"><input type="number" name="banner_order" placeholder="Order" class="form-control" value="0"></div><div class="col-12"><div class="form-check"><input type="checkbox" name="banner_active" checked> Active</div></div></div><button type="submit" name="save_banner" class="btn btn-primary mt-2">Save</button></form></div>
            <div class="table-responsive"><table class="table"><thead><tr><th>Title</th><th>Button</th><th>Status</th><th>Action</th></tr></thead><tbody><?php while($b=$banners->fetch_assoc()): ?><tr id="banner-row-<?=$b['id']?>"><td><?=$b['title']?></td><td><?=$b['button_text']?></td><td><?=$b['is_active']?'✅ Active':'❌'?></td><td><button class="btn btn-danger btn-sm delete-btn" data-table="site_banners" data-id="<?=$b['id']?>"><i class="fas fa-trash"></i></button></td></tr><?php endwhile; ?></tbody></table></div>
        </div></div>
        <?php endif; ?>

        <!-- =========================================================
             STYLES
             ========================================================= -->
        <?php if($tab=='styles'): ?>
        <div class="card"><div class="card-header">Style Manager</div><div class="card-body"><form method="POST"><div class="row g-3"><div class="col-md-4"><label>Primary</label><input type="color" name="primary_color" value="<?=getStyle('primary_color','#2d6a4f')?>" class="form-control"></div><div class="col-md-4"><label>Dark</label><input type="color" name="primary_dark" value="<?=getStyle('primary_dark','#1b4332')?>" class="form-control"></div><div class="col-md-4"><label>Light</label><input type="color" name="primary_light" value="<?=getStyle('primary_light','#52b788')?>" class="form-control"></div><div class="col-md-4"><label>Accent</label><input type="color" name="accent_color" value="<?=getStyle('accent_color','#25D366')?>" class="form-control"></div><div class="col-md-4"><label>Body BG</label><input type="color" name="body_bg" value="<?=getStyle('body_bg','#ffffff')?>" class="form-control"></div><div class="col-md-4"><label>Text Color</label><input type="color" name="text_color" value="<?=getStyle('text_color','#1a1a2e')?>" class="form-control"></div></div><button type="submit" name="save_styles" class="btn btn-primary mt-3">Save</button></form></div></div>
        <?php endif; ?>

        <!-- =========================================================
             DOCTORS
             ========================================================= -->
        <?php if($tab=='doctors'): ?>
        <div class="card"><div class="card-header d-flex justify-content-between"><span>Doctors (<?=$doctors->num_rows?>)</span><button class="btn btn-light btn-sm" onclick="toggleForm('doctorForm');clearDoctorForm()">+ New</button></div><div class="card-body">
            <div id="doctorForm" class="form-section" style="display:none"><form method="POST" enctype="multipart/form-data"><input type="hidden" name="doctor_id" id="doctor_id"><input type="hidden" name="existing_photo" id="existing_photo">
            <div class="row"><div class="col-md-3 text-center"><img id="doctorPhotoPreview" class="preview-image mb-2" style="display:none"><div id="doctorPhotoPlaceholder" class="preview-image bg-light d-flex align-items-center justify-content-center mx-auto mb-2">👨‍⚕️</div><input type="file" name="photo" onchange="previewImage(this,'doctorPhotoPreview','doctorPhotoPlaceholder')" class="form-control"></div>
            <div class="col-md-9"><div class="row g-2"><div class="col-md-6"><input type="text" name="name" id="doc_name" class="form-control" placeholder="Name" required></div><div class="col-md-6"><input type="text" name="degree" id="doc_degree" class="form-control" placeholder="Degree"></div><div class="col-md-6"><input type="text" name="specialization" id="doc_spec" class="form-control" placeholder="Specialization"></div><div class="col-md-6"><input type="text" name="experience" id="doc_exp" class="form-control" placeholder="Experience"></div><div class="col-md-4"><input type="text" name="phone" id="doc_phone" class="form-control" placeholder="Phone"></div><div class="col-md-4"><input type="text" name="whatsapp" id="doc_wa" class="form-control" placeholder="WhatsApp"></div><div class="col-md-4"><input type="number" name="display_order" id="doc_order" class="form-control" placeholder="Order" value="0"></div><div class="col-md-8"><input type="text" name="chamber" id="doc_chamber" class="form-control" placeholder="Chamber"></div><div class="col-md-4"><div class="form-check mt-2"><input type="checkbox" name="is_active" id="doc_active" checked> Active</div></div><div class="col-12"><textarea name="bio" id="doc_bio" class="form-control" placeholder="Bio" rows="2"></textarea></div></div></div></div>
            <button type="submit" name="save_doctor" class="btn btn-primary mt-2">Save</button><button type="button" class="btn btn-secondary" onclick="toggleForm('doctorForm')">Cancel</button></form></div>
            <div class="table-responsive"><table class="table"><thead><tr><th>Photo</th><th>Name</th><th>Degree</th><th>Phone</th><th>Action</th></tr></thead><tbody><?php while($d=$doctors->fetch_assoc()): ?>
            <tr id="doctor-row-<?=$d['id']?>"><td><?php if($d['photo']):?><img src="<?=$d['photo']?>" width="35" style="border-radius:50%"><?php else:?>👨‍⚕️<?php endif;?></td><td><strong><?=$d['name']?></strong></td><td><?=$d['degree']?></td><td><?=$d['phone']?></td>
            <td><button class="btn btn-warning btn-sm" onclick="editDoctor(<?=htmlspecialchars(json_encode($d))?>)">Edit</button><button class="btn btn-danger btn-sm delete-btn" data-table="doctors" data-id="<?=$d['id']?>"><i class="fas fa-trash"></i></button></td></tr>
            <?php endwhile; ?></tbody></table></div>
        </div></div>
        <?php endif; ?>

        <!-- =========================================================
             SERVICES
             ========================================================= -->
        <?php if($tab=='services'): ?>
        <div class="card"><div class="card-header d-flex justify-content-between"><span>Services (<?=$services->num_rows?>)</span><button class="btn btn-light btn-sm" onclick="toggleForm('serviceForm');clearServiceForm()">+ New</button></div><div class="card-body">
            <div id="serviceForm" class="form-section" style="display:none"><form method="POST"><input type="hidden" name="service_id" id="service_id">
            <div class="row g-2"><div class="col-md-6"><input type="text" name="title" id="sv_title" placeholder="Title" class="form-control" required></div><div class="col-md-6"><input type="text" name="icon" id="sv_icon" placeholder="Icon (emoji)" class="form-control" value="💊"></div><div class="col-md-3"><input type="number" step="0.01" name="price" id="sv_price" placeholder="Price" class="form-control" value="0"></div><div class="col-md-3"><input type="color" name="color" id="sv_color" class="form-control" value="#28a745"></div><div class="col-md-3"><input type="number" name="display_order" id="sv_order" placeholder="Order" class="form-control" value="0"></div><div class="col-md-3"><div class="form-check mt-2"><input type="checkbox" name="is_active" id="sv_active" checked> Active</div></div><div class="col-md-6"><input type="text" name="whatsapp_msg" id="sv_wmsg" placeholder="WhatsApp message" class="form-control"></div><div class="col-12"><textarea name="description" id="sv_desc" placeholder="Description" class="form-control" rows="2"></textarea></div></div>
            <button type="submit" name="save_service" class="btn btn-primary mt-2">Save</button><button type="button" class="btn btn-secondary" onclick="toggleForm('serviceForm')">Cancel</button></form></div>
            <div class="table-responsive"><table class="table"><thead><tr><th>Icon</th><th>Title</th><th>Price</th><th>Status</th><th>Action</th></tr></thead><tbody><?php while($s=$services->fetch_assoc()): ?><tr id="service-row-<?=$s['id']?>"><td style="font-size:1.5rem"><?=$s['icon']?></td><td><strong><?=$s['title']?></strong></td><td>৳<?=$s['price']?></td><td><?=$s['is_active']?'✅ Active':'❌'?></td>
            <td><button class="btn btn-warning btn-sm" onclick="editService(<?=htmlspecialchars(json_encode($s))?>)">Edit</button><button class="btn btn-danger btn-sm delete-btn" data-table="services" data-id="<?=$s['id']?>"><i class="fas fa-trash"></i></button></td></tr>
            <?php endwhile; ?></tbody></table></div>
        </div></div>
        <?php endif; ?>

        <!-- =========================================================
             PRODUCTS
             ========================================================= -->
        <?php if($tab=='products'): ?>
        <div class="card"><div class="card-header d-flex justify-content-between"><span>Products (<?=$products->num_rows?>)</span><button class="btn btn-light btn-sm" onclick="toggleForm('productForm');clearProductForm()">+ New</button></div><div class="card-body">
            <div id="productForm" class="form-section" style="display:none"><form method="POST" enctype="multipart/form-data"><input type="hidden" name="product_id" id="product_id"><input type="hidden" name="existing_image" id="existing_image">
            <div class="row"><div class="col-md-3 text-center"><img id="productImagePreview" class="preview-image mb-2" style="display:none"><div id="productImagePlaceholder" class="preview-image bg-light d-flex align-items-center justify-content-center mx-auto mb-2">📦</div><input type="file" name="image" onchange="previewImage(this,'productImagePreview','productImagePlaceholder')" class="form-control"></div>
            <div class="col-md-9"><div class="row g-2"><div class="col-md-8"><input type="text" name="name" id="p_name" placeholder="Name" class="form-control" required></div><div class="col-md-4"><input type="color" name="color" id="p_color" class="form-control" value="#007bff"></div><div class="col-md-4"><input type="number" step="0.01" name="price" id="p_price" placeholder="Price" class="form-control"></div><div class="col-md-4"><input type="number" step="0.01" name="sale_price" id="p_sale" placeholder="Sale Price" class="form-control"></div><div class="col-md-4"><div class="form-check mt-2"><input type="checkbox" name="is_active" id="p_active" checked> Active</div></div><div class="col-12"><input type="text" name="whatsapp_msg" id="p_wmsg" placeholder="WhatsApp message" class="form-control"></div><div class="col-12"><textarea name="description" id="p_desc" placeholder="Description" class="form-control" rows="2"></textarea></div></div></div></div>
            <button type="submit" name="save_product" class="btn btn-primary mt-2">Save</button><button type="button" class="btn btn-secondary" onclick="toggleForm('productForm')">Cancel</button></form></div>
            <div class="table-responsive"><table class="table"><thead><tr><th>Image</th><th>Name</th><th>Price</th><th>Status</th><th>Action</th></tr></thead><tbody><?php while($p=$products->fetch_assoc()): ?><tr id="product-row-<?=$p['id']?>"><td><?php if($p['image']):?><img src="<?=$p['image']?>" width="40" style="border-radius:8px"><?php else:?>📦<?php endif;?></td><td><strong><?=$p['name']?></strong></td><td>৳<?=$p['price']?></td><td><?=$p['is_active']?'✅ Active':'❌'?></td>
            <td><button class="btn btn-warning btn-sm" onclick="editProduct(<?=htmlspecialchars(json_encode($p))?>)">Edit</button><button class="btn btn-danger btn-sm delete-btn" data-table="products" data-id="<?=$p['id']?>"><i class="fas fa-trash"></i></button></td></tr>
            <?php endwhile; ?></tbody></table></div>
        </div></div>
        <?php endif; ?>

        <!-- =========================================================
             CHAMBERS
             ========================================================= -->
        <?php if($tab=='chambers'): ?>
        <div class="card"><div class="card-header d-flex justify-content-between"><span>Chambers (<?=$chambers->num_rows?>)</span><button class="btn btn-light btn-sm" onclick="toggleForm('chamberForm');clearChamberForm()">+ New</button></div><div class="card-body">
            <div id="chamberForm" class="form-section" style="display:none"><form method="POST"><input type="hidden" name="chamber_id" id="chamber_id">
            <div class="row g-2"><div class="col-md-6"><input type="text" name="name" id="c_name" placeholder="Name" class="form-control" required></div><div class="col-md-6"><input type="text" name="city" id="c_city" placeholder="City" class="form-control"></div><div class="col-12"><textarea name="address" id="c_address" placeholder="Address" class="form-control" rows="2"></textarea></div><div class="col-md-6"><input type="text" name="phone" id="c_phone" placeholder="Phone" class="form-control"></div><div class="col-md-6"><input type="text" name="map_link" id="c_map" placeholder="Map Link" class="form-control"></div><div class="col-12"><textarea name="schedule" id="c_schedule" placeholder="Schedule" class="form-control" rows="2"></textarea></div><div class="col-12"><div class="form-check"><input type="checkbox" name="is_active" id="c_active" checked> Active</div></div></div>
            <button type="submit" name="save_chamber" class="btn btn-primary mt-2">Save</button><button type="button" class="btn btn-secondary" onclick="toggleForm('chamberForm')">Cancel</button></form></div>
            <div class="table-responsive"><table class="table"><thead><tr><th>Name</th><th>City</th><th>Phone</th><th>Status</th><th>Action</th></tr></thead><tbody><?php while($ch=$chambers->fetch_assoc()): ?>
            <tr id="chamber-row-<?=$ch['id']?>"><td><strong><?=htmlspecialchars($ch['name'])?></strong></td><td><?=htmlspecialchars($ch['city']??'')?></td><td><?=htmlspecialchars($ch['phone']??'')?></td><td><?=($ch['is_active']??0)?'<span class="badge bg-success">Active</span>':'<span class="badge bg-secondary">Inactive</span>'?></td>
            <td><button class="btn btn-warning btn-sm" onclick="editChamber(<?=htmlspecialchars(json_encode($ch))?>)">Edit</button><button class="btn btn-danger btn-sm delete-btn" data-table="chambers" data-id="<?=$ch['id']?>"><i class="fas fa-trash"></i></button></td></tr>
            <?php endwhile; ?></tbody></table></div>
        </div></div>
        <?php endif; ?>

        <!-- =========================================================
             TUTORIALS
             ========================================================= -->
        <?php if($tab=='tutorials'): ?>
        <div class="card"><div class="card-header d-flex justify-content-between"><span>Tutorials (<?=$tutorials->num_rows?>)</span><button class="btn btn-light btn-sm" onclick="toggleForm('tutorialForm');clearTutorialForm()">+ New</button></div><div class="card-body">
            <div id="tutorialForm" class="form-section" style="display:none"><form method="POST"><input type="hidden" name="tutorial_id" id="tutorial_id">
            <div class="row g-2"><div class="col-md-8"><input type="text" name="title" id="tut_title" placeholder="Title" class="form-control" required></div><div class="col-md-4"><select name="category" id="tut_category" class="form-select"><option value="ordering">🛒 Ordering</option><option value="appointment">📅 Appointment</option><option value="product">📦 Product</option><option value="tracking">🚚 Tracking</option><option value="payment">💰 Payment</option><option value="general">📖 General</option></select></div><div class="col-12"><textarea name="description" id="tut_desc" placeholder="Description" class="form-control" rows="2"></textarea></div><div class="col-md-8"><input type="url" name="youtube_url" id="tut_url" placeholder="YouTube URL" class="form-control" required></div><div class="col-md-2"><input type="text" name="duration" id="tut_duration" placeholder="Duration" class="form-control"></div><div class="col-md-2"><input type="number" name="display_order" id="tut_order" placeholder="Order" class="form-control" value="0"></div><div class="col-12"><div class="form-check"><input type="checkbox" name="is_active" id="tut_active" checked> Active</div></div></div>
            <button type="submit" name="save_tutorial" class="btn btn-primary mt-2">Save</button><button type="button" class="btn btn-secondary" onclick="toggleForm('tutorialForm')">Cancel</button></form></div>
            <div class="table-responsive"><table class="table"><thead><tr><th>ID</th><th>Video</th><th>Title</th><th>Category</th><th>Status</th><th>Action</th></tr></thead><tbody><?php while($tut=$tutorials->fetch_assoc()): ?><tr id="tutorial-row-<?=$tut['id']?>"><td><?=$tut['id']?></td><td><?php if($tut['thumbnail']):?><img src="<?=$tut['thumbnail']?>" width="50" style="border-radius:8px"><?php else:?><i class="fab fa-youtube fa-2x text-danger"></i><?php endif;?></td><td><strong><?=htmlspecialchars($tut['title'])?></strong><br><small><?=substr($tut['description'],0,40)?>...</small></td><td><span class="badge bg-info"><?=ucfirst($tut['category'])?></span></td><td><?=$tut['is_active']?'✅ Active':'❌'?></td>
            <td><button class="btn btn-warning btn-sm" onclick="editTutorial(<?=htmlspecialchars(json_encode($tut))?>)">Edit</button><button class="btn btn-danger btn-sm delete-btn" data-table="tutorials" data-id="<?=$tut['id']?>"><i class="fas fa-trash"></i></button></td></tr>
            <?php endwhile; ?></tbody></table></div>
        </div></div>
        <?php endif; ?>

        <!-- =========================================================
             APPOINTMENTS (AJAX)
             ========================================================= -->
        <?php if($tab=='appointments'): ?>
        <div class="card">
            <div class="card-header">Appointment Management</div>
            <div class="card-body">
                <form method="get" class="row g-2 mb-4">
                    <input type="hidden" name="tab" value="appointments">
                    <div class="col-md-3"><label>Status</label><select name="status" class="form-control"><option value="">All</option><option <?=($status_filter=='pending'?'selected':'')?>>Pending</option><option <?=($status_filter=='confirmed'?'selected':'')?>>Confirmed</option><option <?=($status_filter=='completed'?'selected':'')?>>Completed</option><option <?=($status_filter=='cancelled'?'selected':'')?>>Cancelled</option></select></div>
                    <div class="col-md-3"><label>Chamber</label><select name="chamber" class="form-control"><option value="">All</option><?php $ch_opt=$conn->query("SELECT id,name FROM chambers WHERE status='active'"); while($ch=$ch_opt->fetch_assoc()): ?><option value="<?=$ch['id']?>" <?=($chamber_filter==$ch['id']?'selected':'')?>><?=$ch['name']?></option><?php endwhile; ?></select></div>
                    <div class="col-md-2"><label>From</label><input type="date" name="date_from" class="form-control" value="<?=$date_from?>"></div>
                    <div class="col-md-2"><label>To</label><input type="date" name="date_to" class="form-control" value="<?=$date_to?>"></div>
                    <div class="col-md-2 d-flex align-items-end"><button type="submit" class="btn btn-primary">Filter</button></div>
                </form>
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead><tr><th>ID</th><th>Patient</th><th>Mobile</th><th>Chamber</th><th>Date</th><th>Time</th><th>Category</th><th>Fee</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody id="appointmentsTableBody">
                        <?php while($row = $appointments->fetch_assoc()): 
                            $time = '—'; 
                            if($row['start_time']) $time = date('h:i A', strtotime($row['start_time'])) . ' - ' . date('h:i A', strtotime($row['end_time']));
                            $row_id = $row['id'];
                            $current_status = $row['status'];
                        ?>
                        <tr id="appointment-row-<?= $row_id ?>" data-id="<?= $row_id ?>" data-status="<?= $current_status ?>">
                            <td><?= $row_id ?></td>
                            <td><?= htmlspecialchars($row['patient_name']) ?></td>
                            <td><?= $row['patient_mobile'] ?></td>
                            <td><?= htmlspecialchars($row['chamber_name']) ?></td>
                            <td><?= date('d M Y', strtotime($row['appointment_date'])) ?></td>
                            <td><?= $time ?></td>
                            <td><?= ucfirst(str_replace('_',' ', $row['patient_category'])) ?></td>
                            <td>৳<?= number_format($row['fee'], 2) ?></td>
                            <td><span class="status-badge status-<?= $current_status ?>" id="status-badge-<?= $row_id ?>"><?= ucfirst($current_status) ?></span></td>
                            <td class="action-buttons">
                                <?php if($current_status == 'pending'): ?>
                                    <button class="btn btn-sm btn-success approve-btn" data-id="<?= $row_id ?>"><i class="fas fa-check"></i> Approve</button>
                                    <button class="btn btn-sm btn-danger cancel-btn" data-id="<?= $row_id ?>" data-bs-toggle="modal" data-bs-target="#cancelModal"><i class="fas fa-times"></i> Cancel</button>
                                <?php elseif($current_status == 'confirmed'): ?>
                                    <button class="btn btn-sm btn-info complete-btn" data-id="<?= $row_id ?>"><i class="fas fa-check-double"></i> Complete</button>
                                    <button class="btn btn-sm btn-danger cancel-btn" data-id="<?= $row_id ?>" data-bs-toggle="modal" data-bs-target="#cancelModal"><i class="fas fa-times"></i> Cancel</button>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <!-- Cancel Modal -->
        <div class="modal fade" id="cancelModal" tabindex="-1">
            <div class="modal-dialog"><div class="modal-content"><div class="modal-header bg-danger text-white"><h5>Cancel Appointment</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><textarea id="cancelReason" class="form-control" rows="2" placeholder="Reason for cancellation"></textarea></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button><button type="button" id="confirmCancelBtn" class="btn btn-danger">Confirm Cancel</button></div></div></div>
        </div>
        <?php endif; ?>

        <!-- =========================================================
             BLOG
             ========================================================= -->
        <?php if($tab=='blog'): ?>
        <div class="card"><div class="card-header d-flex justify-content-between"><span>Blog Posts (<?=$blog_posts->num_rows?>)</span><button class="btn btn-light btn-sm" onclick="toggleForm('postForm');clearPostForm()">+ New Post</button></div><div class="card-body">
            <div id="postForm" class="form-section" style="display:none"><form method="POST" enctype="multipart/form-data"><input type="hidden" name="post_id" id="post_id"><input type="hidden" name="existing_image" id="existing_image">
            <div class="row"><div class="col-md-3 text-center"><img id="postImagePreview" class="preview-image mb-2" style="display:none"><div id="postImagePlaceholder" class="preview-image bg-light d-flex align-items-center justify-content-center mx-auto mb-2">📷</div><input type="file" name="image" onchange="previewImage(this,'postImagePreview','postImagePlaceholder')" class="form-control"></div>
            <div class="col-md-9"><div class="row g-2"><div class="col-md-6"><input type="text" name="title" id="post_title" placeholder="Title" class="form-control" required></div><div class="col-md-6"><input type="text" name="slug" id="post_slug" placeholder="Slug" class="form-control" required></div><div class="col-md-6"><select name="category_id" id="post_cat" class="form-control"><?php $cats=$conn->query("SELECT * FROM blog_categories ORDER BY name"); while($cat=$cats->fetch_assoc()): ?><option value="<?=$cat['id']?>"><?=$cat['name']?></option><?php endwhile; ?></select></div><div class="col-md-6"><input type="text" name="tags" id="post_tags" placeholder="Tags (comma separated)" class="form-control"></div><div class="col-md-6"><select name="status" id="post_status" class="form-control"><option value="published">Published</option><option value="draft">Draft</option></select></div><div class="col-12"><textarea name="excerpt" id="post_excerpt" placeholder="Excerpt" class="form-control" rows="2"></textarea></div><div class="col-12"><textarea name="content" id="post_content" placeholder="Full content (HTML allowed)" class="form-control" rows="6"></textarea></div><div class="col-12"><hr><h6>SEO Settings</h6></div><div class="col-12"><input type="text" name="meta_title" id="post_meta_title" placeholder="Meta Title" class="form-control"></div><div class="col-12"><input type="text" name="meta_keywords" id="post_meta_keywords" placeholder="Meta Keywords" class="form-control"></div><div class="col-12"><textarea name="meta_description" id="post_meta_description" placeholder="Meta Description" class="form-control" rows="2"></textarea></div></div></div></div>
            <button type="submit" name="save_blog_post" class="btn btn-primary mt-2">Save</button><button type="button" class="btn btn-secondary" onclick="toggleForm('postForm')">Cancel</button></form></div>
            <div class="table-responsive"><table class="table"><thead><tr><th>ID</th><th>Image</th><th>Title</th><th>Category</th><th>Status</th><th>Date</th><th>Action</th></tr></thead>
            <tbody><?php while($p=$blog_posts->fetch_assoc()): ?>
            <tr id="blog-row-<?=$p['id']?>"><td><?=$p['id']?></td><td><?php if(isset($p['image']) && $p['image']):?><img src="<?=$p['image']?>" width="40" style="border-radius:8px"><?php else:?>📷<?php endif;?></td><td><strong><?=htmlspecialchars($p['title'])?></strong></td><td><?=$p['category_name']?></td><td><?=$p['status']=='published'?'✅ Published':'📝 Draft'?></td><td><?=date('d M Y',strtotime($p['created_at']))?></td>
            <td><button class="btn btn-warning btn-sm" onclick="editPost(<?=htmlspecialchars(json_encode($p))?>)">Edit</button><button class="btn btn-danger btn-sm delete-btn" data-table="blog_posts" data-id="<?=$p['id']?>"><i class="fas fa-trash"></i></button></td></tr>
            <?php endwhile; ?></tbody></table></div>
        </div></div>
        <?php endif; ?>

        <!-- =========================================================
             BLOG CATEGORIES
             ========================================================= -->
        <?php if($tab=='blog_categories'): ?>
        <div class="card"><div class="card-header d-flex justify-content-between"><span>Blog Categories</span><button class="btn btn-light btn-sm" onclick="toggleForm('catForm');clearCatForm()">+ New Category</button></div><div class="card-body">
            <div id="catForm" class="form-section" style="display:none"><form method="POST"><input type="hidden" name="category_id" id="category_id">
            <div class="row"><div class="col-md-6"><input type="text" name="name" id="cat_name" placeholder="Name" class="form-control" required></div><div class="col-md-6"><input type="text" name="slug" id="cat_slug" placeholder="Slug" class="form-control"></div><div class="col-12"><textarea name="description" id="cat_desc" placeholder="Description" class="form-control" rows="2"></textarea></div><div class="col-12"><input type="number" name="display_order" id="cat_order" placeholder="Order" class="form-control" value="0"></div></div>
            <button type="submit" name="save_blog_category" class="btn btn-primary mt-2">Save</button><button type="button" class="btn btn-secondary" onclick="toggleForm('catForm')">Cancel</button></form></div>
            <div class="table-responsive"><table class="table"><thead><tr><th>ID</th><th>Name</th><th>Slug</th><th>Posts</th><th>Action</th></tr></thead><tbody><?php $cats_all=$conn->query("SELECT c.*, (SELECT COUNT(*) FROM blog_posts WHERE category_id=c.id) as post_count FROM blog_categories c ORDER BY c.display_order"); while($cat=$cats_all->fetch_assoc()): ?>
            <tr id="category-row-<?=$cat['id']?>"><td><?=$cat['id']?></td><td><strong><?=$cat['name']?></strong></td><td><?=$cat['slug']?></td><td><?=$cat['post_count']?></td>
            <td><button class="btn btn-warning btn-sm" onclick="editCat(<?=htmlspecialchars(json_encode($cat))?>)">Edit</button><button class="btn btn-danger btn-sm delete-btn" data-table="blog_categories" data-id="<?=$cat['id']?>"><i class="fas fa-trash"></i></button></td></tr>
            <?php endwhile; ?></tbody></table></div>
        </div></div>
        <?php endif; ?>

        <!-- =========================================================
             CUSTOMERS
             ========================================================= -->
        <?php if($tab=='customers'): ?>
        <div class="card"><div class="card-header">Customers (<?=$customers->num_rows?>)</div><div class="card-body p-0"><div class="table-responsive"><table class="table"><thead><tr><th>Name</th><th>Phone</th><th>Email</th><th>Interest</th><th>Date</th></tr></thead><tbody><?php while($c=$customers->fetch_assoc()): ?><tr><td><?=$c['name']?></td><td><?=$c['phone']?></td><td><?=$c['email']?></td><td><?=$c['interest']?></td><td><?=date('d/m/Y',strtotime($c['created_at']))?></td></tr><?php endwhile; ?></tbody></table></div></div></div>
        <?php endif; ?>

        <!-- =========================================================
             AFFILIATES (with AJAX)
             ========================================================= -->
        <?php if($tab=='affiliates'): ?>
        <div class="card">
            <div class="card-header">
                <ul class="nav nav-pills card-header-pills">
                    <li class="nav-item"><a class="nav-link text-white <?=$subtab=='list'?'active bg-light text-dark':''?>" href="?tab=affiliates&subtab=list"><i class="fas fa-users"></i> Affiliates</a></li>
                    <li class="nav-item"><a class="nav-link text-white <?=$subtab=='referrals'?'active bg-light text-dark':''?>" href="?tab=affiliates&subtab=referrals"><i class="fas fa-link"></i> Referrals</a></li>
                    <li class="nav-item"><a class="nav-link text-white <?=$subtab=='payouts'?'active bg-light text-dark':''?>" href="?tab=affiliates&subtab=payouts"><i class="fas fa-money-bill-wave"></i> Payouts</a></li>
                </ul>
            </div>
            <div class="card-body">
                <!-- AFFILIATES LIST -->
                <?php if($subtab=='list'): ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead><tr><th>ID</th><th>Name</th><th>Email</th><th>Code</th><th>Commission</th><th>Earnings</th><th>Balance</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody id="affiliatesTableBody">
                        <?php while($a = $affiliates->fetch_assoc()): ?>
                            <tr id="affiliate-row-<?= $a['id'] ?>">
                                <td><?= $a['id'] ?></td>
                                <td><strong><?= htmlspecialchars($a['name']) ?></strong></td>
                                <td><?= $a['email'] ?></td>
                                <td><code><?= $a['referral_code'] ?></code></td>
                                <td><span class="commission-rate" data-id="<?= $a['id'] ?>"><?= $a['commission_rate'] ?>%</span></td>
                                <td>৳<?= number_format($a['total_earnings'], 2) ?></td>
                                <td>৳<?= number_format($a['balance'], 2) ?></td>
                                <td><span class="badge badge-<?= $a['status'] ?>" id="status-badge-<?= $a['id'] ?>"><?= ucfirst($a['status']) ?></span></td>
                                <td>
                                    <button class="btn btn-sm btn-warning toggle-status" data-id="<?= $a['id'] ?>" data-status="<?= $a['status'] == 'active' ? 'inactive' : 'active' ?>">
                                        <i class="fas fa-toggle-<?= $a['status']=='active'?'on':'off' ?>"></i>
                                    </button>
                                    <button class="btn btn-sm btn-info edit-commission" data-id="<?= $a['id'] ?>" data-name="<?= htmlspecialchars($a['name']) ?>" data-rate="<?= $a['commission_rate'] ?>">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn btn-sm btn-danger delete-btn" data-table="affiliates" data-id="<?= $a['id'] ?>"><i class="fas fa-trash"></i></button>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>

                <!-- REFERRALS LIST -->
                <?php if($subtab=='referrals'): ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead><tr><th>ID</th><th>Affiliate</th><th>Type</th><th>Customer</th><th>Order</th><th>Amount</th><th>Commission</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody id="referralsTableBody">
                        <?php while($r = $referrals->fetch_assoc()): ?>
                            <tr id="referral-row-<?= $r['id'] ?>">
                                <td><?= $r['id'] ?></td>
                                <td><?= htmlspecialchars($r['affiliate_name']) ?></td>
                                <td><span class="badge bg-secondary"><?= ucfirst($r['referral_type'] ?? 'general') ?></span></td>
                                <td><?= htmlspecialchars($r['referred_customer_email'] ?? 'N/A') ?></td>
                                <td>#<?= htmlspecialchars($r['order_number'] ?? '—') ?></td>
                                <td>৳<?= number_format($r['total_amount'] ?? 0, 2) ?></td>
                                <td>৳<?= number_format($r['commission_amount'], 2) ?></td>
                                <td><span class="badge badge-<?= $r['status'] ?>" id="ref-status-<?= $r['id'] ?>"><?= ucfirst($r['status']) ?></span></td>
                                <td>
                                    <?php if($r['status'] == 'pending'): ?>
                                        <button class="btn btn-sm btn-success update-referral" data-id="<?= $r['id'] ?>" data-status="approved"><i class="fas fa-check"></i></button>
                                        <button class="btn btn-sm btn-danger update-referral" data-id="<?= $r['id'] ?>" data-status="cancelled"><i class="fas fa-times"></i></button>
                                    <?php elseif($r['status'] == 'approved'): ?>
                                        <button class="btn btn-sm btn-info update-referral" data-id="<?= $r['id'] ?>" data-status="paid"><i class="fas fa-dollar-sign"></i></button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>

                <!-- PAYOUTS LIST -->
                <?php if($subtab=='payouts'): ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead><tr><th>ID</th><th>Affiliate</th><th>Amount</th><th>Method</th><th>Status</th><th>Requested</th><th>Actions</th></tr></thead>
                        <tbody id="payoutsTableBody">
                        <?php while($p = $payouts->fetch_assoc()): ?>
                            <tr id="payout-row-<?= $p['id'] ?>">
                                <td><?= $p['id'] ?></td>
                                <td><?= htmlspecialchars($p['affiliate_name']) ?></td>
                                <td><strong>৳<?= number_format($p['amount'], 2) ?></strong></td>
                                <td><?= strtoupper($p['payment_method']) ?></td>
                                <td><span class="badge badge-<?= $p['status'] == 'completed' ? 'success' : ($p['status'] == 'pending' ? 'warning' : 'secondary') ?>" id="payout-status-<?= $p['id'] ?>"><?= ucfirst($p['status']) ?></span></td>
                                <td><?= date('d M Y', strtotime($p['requested_at'])) ?></td>
                                <td>
                                    <?php if($p['status'] == 'pending'): ?>
                                        <button class="btn btn-sm btn-success update-payout" data-id="<?= $p['id'] ?>" data-status="completed"><i class="fas fa-check"></i> Approve</button>
                                        <button class="btn btn-sm btn-danger update-payout" data-id="<?= $p['id'] ?>" data-status="failed"><i class="fas fa-times"></i> Reject</button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Edit Commission Modal -->
        <div class="modal fade" id="commissionModal" tabindex="-1">
            <div class="modal-dialog"><div class="modal-content">
                <div class="modal-header"><h5><i class="fas fa-edit"></i> Edit Commission Rate</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" id="editAffiliateId">
                    <label>Affiliate: <strong id="editAffiliateName"></strong></label>
                    <div class="input-group mt-2">
                        <input type="number" id="editCommissionRate" class="form-control" step="0.1" min="1" max="50">
                        <span class="input-group-text">%</span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" id="saveCommission" class="btn btn-primary">Update</button>
                </div>
            </div></div>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- =========================================================
     TOAST CONTAINER
     ========================================================= -->
<div class="toast-container" id="toastContainer"></div>

<!-- =========================================================
     SCRIPTS
     ========================================================= -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// =========================================================
// UTILITY FUNCTIONS
// =========================================================
function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('show');
}

function toggleForm(id) {
    const f = document.getElementById(id);
    if (f) f.style.display = f.style.display == 'none' ? 'block' : 'none';
}

function previewImage(input, previewId, placeholderId) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const p = document.getElementById(previewId);
            if (p) {
                p.src = e.target.result;
                p.style.display = 'block';
                if (placeholderId) document.getElementById(placeholderId).style.display = 'none';
            }
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// =========================================================
// TOAST SYSTEM
// =========================================================
function showToast(message, type = 'success') {
    const container = document.getElementById('toastContainer');
    if (!container) return;
    const toast = document.createElement('div');
    toast.className = 'toast-item' + (type === 'danger' ? ' danger' : type === 'warning' ? ' warning' : '');
    const icon = type === 'success' ? '✅' : type === 'danger' ? '❌' : '⚠️';
    toast.innerHTML = `<span>${icon}</span><span>${message}</span><button class="close-btn" onclick="this.parentElement.remove()">&times;</button>`;
    container.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
}

// =========================================================
// AFFILIATE FUNCTIONS
// =========================================================

// Toggle affiliate status
$('.toggle-status').click(function() {
    const $btn = $(this);
    const id = $btn.data('id');
    const status = $btn.data('status');
    if (!confirm(`Change affiliate status to ${status}?`)) return;
    const originalHtml = $btn.html();
    $btn.html('<i class="fas fa-spinner fa-spin"></i>').prop('disabled', true);
    
    $.post(window.location.href, {
        ajax_action: 'update_affiliate_status',
        affiliate_id: id,
        status: status
    }, function(res) {
        if (res.success) {
            showToast(res.message, 'success');
            const badge = $('#status-badge-'+id);
            badge.removeClass('badge-active badge-inactive');
            badge.addClass('badge-'+status);
            badge.text(status.charAt(0).toUpperCase() + status.slice(1));
            $btn.data('status', status == 'active' ? 'inactive' : 'active');
            $btn.html('<i class="fas fa-toggle-' + (status == 'active' ? 'on' : 'off') + '"></i>');
        } else {
            showToast(res.message || 'Error', 'danger');
        }
        $btn.html(originalHtml).prop('disabled', false);
    }).fail(function() {
        showToast('Server error', 'danger');
        $btn.html(originalHtml).prop('disabled', false);
    });
});

// Edit commission modal
$('.edit-commission').click(function() {
    const id = $(this).data('id');
    const name = $(this).data('name');
    const rate = $(this).data('rate');
    $('#editAffiliateId').val(id);
    $('#editAffiliateName').text(name);
    $('#editCommissionRate').val(rate);
    new bootstrap.Modal(document.getElementById('commissionModal')).show();
});

$('#saveCommission').click(function() {
    const id = $('#editAffiliateId').val();
    const rate = $('#editCommissionRate').val();
    if (!rate || rate < 1 || rate > 50) {
        showToast('Please enter a valid rate (1-50)', 'warning');
        return;
    }
    $('#commissionModal').modal('hide');
    $.post(window.location.href, {
        ajax_action: 'update_commission',
        affiliate_id: id,
        commission_rate: rate
    }, function(res) {
        if (res.success) {
            showToast(res.message, 'success');
            $(`.commission-rate[data-id="${id}"]`).text(rate + '%');
        } else {
            showToast(res.message || 'Error', 'danger');
        }
    }).fail(function() {
        showToast('Server error', 'danger');
    });
});

// Update referral status
$('.update-referral').click(function() {
    const $btn = $(this);
    const id = $btn.data('id');
    const status = $btn.data('status');
    if (!confirm(`Change referral status to ${status}?`)) return;
    const originalHtml = $btn.html();
    $btn.html('<i class="fas fa-spinner fa-spin"></i>').prop('disabled', true);
    
    $.post(window.location.href, {
        ajax_action: 'update_referral_status',
        referral_id: id,
        status: status
    }, function(res) {
        if (res.success) {
            showToast(res.message, 'success');
            const badge = $('#ref-status-'+id);
            badge.removeClass('badge-pending badge-approved badge-paid badge-cancelled');
            badge.addClass('badge-'+status);
            badge.text(status.charAt(0).toUpperCase() + status.slice(1));
            $('#referral-row-'+id+' td:last-child').html('<span class="text-muted">✓</span>');
        } else {
            showToast(res.message || 'Error', 'danger');
        }
        $btn.html(originalHtml).prop('disabled', false);
    }).fail(function() {
        showToast('Server error', 'danger');
        $btn.html(originalHtml).prop('disabled', false);
    });
});

// Update payout status
$('.update-payout').click(function() {
    const $btn = $(this);
    const id = $btn.data('id');
    const status = $btn.data('status');
    const action = status == 'completed' ? 'approve' : 'reject';
    if (!confirm(`Are you sure to ${action} this payout?`)) return;
    const originalHtml = $btn.html();
    $btn.html('<i class="fas fa-spinner fa-spin"></i>').prop('disabled', true);
    
    $.post(window.location.href, {
        ajax_action: 'update_payout_status',
        payout_id: id,
        status: status
    }, function(res) {
        if (res.success) {
            showToast(res.message, 'success');
            const badge = $('#payout-status-'+id);
            badge.removeClass('badge-pending badge-success badge-secondary');
            if (status == 'completed') {
                badge.addClass('badge-success');
                badge.text('Completed');
            } else if (status == 'failed') {
                badge.addClass('badge-secondary');
                badge.text('Failed');
            }
            $('#payout-row-'+id+' td:last-child').html('<span class="text-muted">✓</span>');
        } else {
            showToast(res.message || 'Error', 'danger');
        }
        $btn.html(originalHtml).prop('disabled', false);
    }).fail(function() {
        showToast('Server error', 'danger');
        $btn.html(originalHtml).prop('disabled', false);
    });
});

// =========================================================
// APPOINTMENT FUNCTIONS
// =========================================================
function processAction(appointmentId, action, reason = '') {
    const btn = $(`.${action}-btn[data-id="${appointmentId}"]`);
    const originalHtml = btn.html();
    btn.html('<i class="fas fa-spinner fa-spin"></i>').prop('disabled', true).addClass('btn-loading');
    
    $.post(window.location.href, {
        ajax_action: 'update_appointment_status',
        appointment_id: appointmentId,
        action: action,
        reason: reason
    }, function(res) {
        if (res.success) {
            showToast(res.message, 'success');
            let newStatus = '', newStatusText = '';
            if (action === 'approve') { newStatus = 'confirmed'; newStatusText = 'Confirmed'; }
            else if (action === 'complete') { newStatus = 'completed'; newStatusText = 'Completed'; }
            else if (action === 'cancel') { newStatus = 'cancelled'; newStatusText = 'Cancelled'; }
            if (newStatus) {
                const badge = $('#status-badge-'+appointmentId);
                badge.removeClass('status-pending status-confirmed status-completed status-cancelled');
                badge.addClass('status-'+newStatus);
                badge.text(newStatusText);
                const actionCell = $('#appointment-row-'+appointmentId+' .action-buttons');
                if (newStatus === 'confirmed') {
                    actionCell.html('<button class="btn btn-sm btn-info complete-btn" data-id="'+appointmentId+'"><i class="fas fa-check-double"></i> Complete</button> <button class="btn btn-sm btn-danger cancel-btn" data-id="'+appointmentId+'" data-bs-toggle="modal" data-bs-target="#cancelModal"><i class="fas fa-times"></i> Cancel</button>');
                } else if (newStatus === 'completed' || newStatus === 'cancelled') {
                    actionCell.html('<span class="text-muted">—</span>');
                }
            }
        } else {
            showToast(res.message || 'Error', 'danger');
        }
        btn.html(originalHtml).prop('disabled', false).removeClass('btn-loading');
    }).fail(function() {
        showToast('Server error. Please try again.', 'danger');
        btn.html(originalHtml).prop('disabled', false).removeClass('btn-loading');
    });
}

$(document).on('click', '.approve-btn, .complete-btn', function(e) {
    e.preventDefault();
    const id = $(this).data('id');
    const action = $(this).hasClass('approve-btn') ? 'approve' : 'complete';
    if (confirm(`Are you sure to ${action} this appointment?`)) {
        processAction(id, action);
    }
});

let currentCancelId = null;
$(document).on('click', '.cancel-btn', function() {
    currentCancelId = $(this).data('id');
});
$('#confirmCancelBtn').click(function() {
    const reason = $('#cancelReason').val();
    if (!reason.trim()) { alert('Please provide a reason'); return; }
    $('#cancelModal').modal('hide');
    processAction(currentCancelId, 'cancel', reason);
});

// =========================================================
// DELETE FUNCTION
// =========================================================
$(document).on('click', '.delete-btn', function(e) {
    e.preventDefault();
    const $btn = $(this);
    const table = $btn.data('table');
    const id = $btn.data('id');
    if (!table || !id) return;
    if (!confirm(`Delete this record from ${table}?`)) return;
    const originalHtml = $btn.html();
    $btn.html('<i class="fas fa-spinner fa-spin"></i>').prop('disabled', true).addClass('btn-loading');
    
    $.post(window.location.href, {
        ajax_action: 'delete',
        table: table,
        id: id
    }, function(res) {
        if (res.success) {
            showToast(res.message, 'success');
            const row = $(`#${table}-row-${id}`);
            if (row.length) {
                row.fadeOut(300, function() { $(this).remove(); });
            } else {
                location.reload();
            }
        } else {
            showToast(res.message || 'Error deleting', 'danger');
        }
        $btn.html(originalHtml).prop('disabled', false).removeClass('btn-loading');
    }).fail(function() {
        showToast('Server error. Please try again.', 'danger');
        $btn.html(originalHtml).prop('disabled', false).removeClass('btn-loading');
    });
});

// =========================================================
// SIDEBAR CLOSE ON MOBILE
// =========================================================
document.addEventListener('click', function(e) {
    const sidebar = document.getElementById('sidebar');
    const toggle = document.getElementById('menuToggle');
    if (window.innerWidth <= 992 && sidebar.classList.contains('show')) {
        if (!sidebar.contains(e.target) && !toggle.contains(e.target)) {
            sidebar.classList.remove('show');
        }
    }
});

// Keyboard shortcut: ESC to close sidebar
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const sidebar = document.getElementById('sidebar');
        if (sidebar.classList.contains('show')) {
            sidebar.classList.remove('show');
        }
    }
});

// =========================================================
// EDIT FUNCTIONS (for all modules)
// =========================================================
function editDoctor(d) {
    toggleForm('doctorForm');
    document.getElementById('doctor_id').value = d.id;
    document.getElementById('doc_name').value = d.name;
    document.getElementById('doc_degree').value = d.degree || '';
    document.getElementById('doc_spec').value = d.specialization || '';
    document.getElementById('doc_exp').value = d.experience || '';
    document.getElementById('doc_phone').value = d.phone || '';
    document.getElementById('doc_wa').value = d.whatsapp || '';
    document.getElementById('doc_chamber').value = d.chamber || '';
    document.getElementById('doc_bio').value = d.bio || '';
    document.getElementById('doc_order').value = d.display_order || 0;
    document.getElementById('doc_active').checked = (d.is_active == 1);
    document.getElementById('existing_photo').value = d.photo || '';
    if (d.photo) {
        document.getElementById('doctorPhotoPreview').src = d.photo;
        document.getElementById('doctorPhotoPreview').style.display = 'block';
        document.getElementById('doctorPhotoPlaceholder').style.display = 'none';
    } else {
        document.getElementById('doctorPhotoPreview').style.display = 'none';
        document.getElementById('doctorPhotoPlaceholder').style.display = 'flex';
    }
}

function clearDoctorForm() {
    document.getElementById('doctor_id').value = '';
    document.getElementById('doc_name').value = '';
    document.getElementById('doc_degree').value = '';
    document.getElementById('doc_spec').value = '';
    document.getElementById('doc_exp').value = '';
    document.getElementById('doc_phone').value = '';
    document.getElementById('doc_wa').value = '';
    document.getElementById('doc_chamber').value = '';
    document.getElementById('doc_bio').value = '';
    document.getElementById('doc_order').value = '0';
    document.getElementById('doc_active').checked = true;
    document.getElementById('existing_photo').value = '';
    document.getElementById('doctorPhotoPreview').style.display = 'none';
    document.getElementById('doctorPhotoPlaceholder').style.display = 'flex';
}

function editService(s) {
    toggleForm('serviceForm');
    document.getElementById('service_id').value = s.id;
    document.getElementById('sv_title').value = s.title;
    document.getElementById('sv_icon').value = s.icon;
    document.getElementById('sv_price').value = s.price;
    document.getElementById('sv_color').value = s.color;
    document.getElementById('sv_order').value = s.display_order;
    document.getElementById('sv_wmsg').value = s.whatsapp_msg || '';
    document.getElementById('sv_desc').value = s.description || '';
    document.getElementById('sv_active').checked = (s.is_active == 1);
}

function clearServiceForm() {
    document.getElementById('service_id').value = '';
    document.getElementById('sv_title').value = '';
    document.getElementById('sv_icon').value = '💊';
    document.getElementById('sv_price').value = '0';
    document.getElementById('sv_color').value = '#28a745';
    document.getElementById('sv_order').value = '0';
    document.getElementById('sv_wmsg').value = '';
    document.getElementById('sv_desc').value = '';
    document.getElementById('sv_active').checked = true;
}

function editProduct(p) {
    toggleForm('productForm');
    document.getElementById('product_id').value = p.id;
    document.getElementById('p_name').value = p.name;
    document.getElementById('p_color').value = p.color;
    document.getElementById('p_price').value = p.price;
    document.getElementById('p_sale').value = p.sale_price;
    document.getElementById('p_wmsg').value = p.whatsapp_msg || '';
    document.getElementById('p_desc').value = p.description || '';
    document.getElementById('p_active').checked = (p.is_active == 1);
    document.getElementById('existing_image').value = p.image || '';
    if (p.image) {
        document.getElementById('productImagePreview').src = p.image;
        document.getElementById('productImagePreview').style.display = 'block';
        document.getElementById('productImagePlaceholder').style.display = 'none';
    } else {
        document.getElementById('productImagePreview').style.display = 'none';
        document.getElementById('productImagePlaceholder').style.display = 'flex';
    }
}

function clearProductForm() {
    document.getElementById('product_id').value = '';
    document.getElementById('p_name').value = '';
    document.getElementById('p_color').value = '#007bff';
    document.getElementById('p_price').value = '0';
    document.getElementById('p_sale').value = '0';
    document.getElementById('p_wmsg').value = '';
    document.getElementById('p_desc').value = '';
    document.getElementById('p_active').checked = true;
    document.getElementById('existing_image').value = '';
    document.getElementById('productImagePreview').style.display = 'none';
    document.getElementById('productImagePlaceholder').style.display = 'flex';
}

function editChamber(c) {
    toggleForm('chamberForm');
    document.getElementById('chamber_id').value = c.id;
    document.getElementById('c_name').value = c.name;
    document.getElementById('c_city').value = c.city || '';
    document.getElementById('c_address').value = c.address || '';
    document.getElementById('c_phone').value = c.phone || '';
    document.getElementById('c_map').value = c.map_link || '';
    document.getElementById('c_schedule').value = c.schedule || '';
    document.getElementById('c_active').checked = (c.is_active == 1);
}

function clearChamberForm() {
    document.getElementById('chamber_id').value = '';
    document.getElementById('c_name').value = '';
    document.getElementById('c_city').value = '';
    document.getElementById('c_address').value = '';
    document.getElementById('c_phone').value = '';
    document.getElementById('c_map').value = '';
    document.getElementById('c_schedule').value = '';
    document.getElementById('c_active').checked = true;
}

function editTutorial(t) {
    toggleForm('tutorialForm');
    document.getElementById('tutorial_id').value = t.id;
    document.getElementById('tut_title').value = t.title;
    document.getElementById('tut_desc').value = t.description || '';
    document.getElementById('tut_url').value = t.youtube_url;
    document.getElementById('tut_category').value = t.category;
    document.getElementById('tut_duration').value = t.duration || '';
    document.getElementById('tut_order').value = t.display_order;
    document.getElementById('tut_active').checked = (t.is_active == 1);
}

function clearTutorialForm() {
    document.getElementById('tutorial_id').value = '';
    document.getElementById('tut_title').value = '';
    document.getElementById('tut_desc').value = '';
    document.getElementById('tut_url').value = '';
    document.getElementById('tut_category').value = 'general';
    document.getElementById('tut_duration').value = '';
    document.getElementById('tut_order').value = '0';
    document.getElementById('tut_active').checked = true;
}

function editPost(p) {
    toggleForm('postForm');
    document.getElementById('post_id').value = p.id;
    document.getElementById('post_title').value = p.title;
    document.getElementById('post_slug').value = p.slug;
    document.getElementById('post_cat').value = p.category_id;
    document.getElementById('post_tags').value = p.tags || '';
    document.getElementById('post_status').value = p.status;
    document.getElementById('post_excerpt').value = p.excerpt || '';
    document.getElementById('post_content').value = p.content;
    document.getElementById('post_meta_title').value = p.meta_title || '';
    document.getElementById('post_meta_keywords').value = p.meta_keywords || '';
    document.getElementById('post_meta_description').value = p.meta_description || '';
    document.getElementById('existing_image').value = p.image || '';
    if (p.image) {
        document.getElementById('postImagePreview').src = p.image;
        document.getElementById('postImagePreview').style.display = 'block';
        document.getElementById('postImagePlaceholder').style.display = 'none';
    } else {
        document.getElementById('postImagePreview').style.display = 'none';
        document.getElementById('postImagePlaceholder').style.display = 'flex';
    }
}

function clearPostForm() {
    document.getElementById('post_id').value = '';
    document.getElementById('post_title').value = '';
    document.getElementById('post_slug').value = '';
    document.getElementById('post_cat').selectedIndex = 0;
    document.getElementById('post_tags').value = '';
    document.getElementById('post_status').value = 'draft';
    document.getElementById('post_excerpt').value = '';
    document.getElementById('post_content').value = '';
    document.getElementById('post_meta_title').value = '';
    document.getElementById('post_meta_keywords').value = '';
    document.getElementById('post_meta_description').value = '';
    document.getElementById('existing_image').value = '';
    document.getElementById('postImagePreview').style.display = 'none';
    document.getElementById('postImagePlaceholder').style.display = 'flex';
}

function editCat(c) {
    toggleForm('catForm');
    document.getElementById('category_id').value = c.id;
    document.getElementById('cat_name').value = c.name;
    document.getElementById('cat_slug').value = c.slug || '';
    document.getElementById('cat_desc').value = c.description || '';
    document.getElementById('cat_order').value = c.display_order;
}

function clearCatForm() {
    document.getElementById('category_id').value = '';
    document.getElementById('cat_name').value = '';
    document.getElementById('cat_slug').value = '';
    document.getElementById('cat_desc').value = '';
    document.getElementById('cat_order').value = '0';
}
</script>
</body>
</html>