<?php
// ============================================
// PATIENT DASHBOARD - COMPLETE FIX
// Path: /public_html/Appointment/opd/dashboard.php
// ============================================

// --- Start Session ---
session_start();

// --- Check if patient is logged in ---
if (!isset($_SESSION['opd_patient'])) {
    header('Location: login.php');
    exit;
}

// --- Include Config ---
require_once '../config.php';

// --- Define $brand FIRST ---
$brand = array(
    'name' => 'ওয়ান হোমিওপ্যাথি',
    'slogan' => 'প্রাকৃতিক চিকিৎসায় সুস্থ জীবন',
    'phone' => '017XXXXXXXX',
    'whatsapp' => '017XXXXXXXX',
    'email' => 'info@example.com',
    'address' => 'ঢাকা, বাংলাদেশ',
    'logo' => '',
    'facebook' => '',
    'youtube' => '',
    'hero_image' => 'assets/images/hero-bg.jpg'
);

// Try to fetch from database
try {
    $brand_result = mysqli_query($conn, "SELECT * FROM brand LIMIT 1");
    if ($brand_result && mysqli_num_rows($brand_result) > 0) {
        $brand_data = mysqli_fetch_assoc($brand_result);
        foreach ($brand_data as $key => $value) {
            if (!empty($value)) {
                $brand[$key] = $value;
            }
        }
    }
} catch (Exception $e) {
    // Table might not exist, use defaults
}

// --- Get Patient Info ---
$patient_id = $_SESSION['opd_patient'];
$patient_name = $_SESSION['opd_patient_name'] ?? 'রোগী';

$patient_query = mysqli_query($conn, "SELECT * FROM opd_patients WHERE id = '$patient_id'");
$patient = mysqli_fetch_assoc($patient_query);

// --- Get Appointments ---
$appointments = array();
$appointments_query = "SELECT a.*, c.name as chamber_name, c.address 
                       FROM appointments a 
                       LEFT JOIN chambers c ON a.chamber_id = c.id 
                       WHERE a.patient_id = '$patient_id' 
                       ORDER BY a.appointment_date DESC 
                       LIMIT 10";
$appointments_result = mysqli_query($conn, $appointments_query);
if ($appointments_result) {
    while ($row = mysqli_fetch_assoc($appointments_result)) {
        $appointments[] = $row;
    }
}

// --- FIXED: Get Orders ---
$orders = array();

// First, check what columns exist in the orders table
$columns_check = mysqli_query($conn, "SHOW COLUMNS FROM orders");
$order_columns = array();
if ($columns_check) {
    while ($col = mysqli_fetch_assoc($columns_check)) {
        $order_columns[] = $col['Field'];
    }
}

// Build query based on available columns
if (in_array('product_id', $order_columns)) {
    // If product_id exists, join with products
    $orders_query = "SELECT o.*, p.name as product_name 
                     FROM orders o 
                     LEFT JOIN products p ON o.product_id = p.id 
                     WHERE o.patient_id = '$patient_id' 
                     ORDER BY o.created_at DESC 
                     LIMIT 5";
} elseif (in_array('product_name', $order_columns)) {
    // If product_name exists directly in orders
    $orders_query = "SELECT o.*, o.product_name 
                     FROM orders o 
                     WHERE o.patient_id = '$patient_id' 
                     ORDER BY o.created_at DESC 
                     LIMIT 5";
} elseif (in_array('service_name', $order_columns)) {
    // If service_name exists
    $orders_query = "SELECT o.*, o.service_name as product_name 
                     FROM orders o 
                     WHERE o.patient_id = '$patient_id' 
                     ORDER BY o.created_at DESC 
                     LIMIT 5";
} else {
    // Fallback: just get orders without product name
    $orders_query = "SELECT o.*, 'পণ্য' as product_name 
                     FROM orders o 
                     WHERE o.patient_id = '$patient_id' 
                     ORDER BY o.created_at DESC 
                     LIMIT 5";
}

$orders_result = mysqli_query($conn, $orders_query);
if ($orders_result) {
    while ($row = mysqli_fetch_assoc($orders_result)) {
        $orders[] = $row;
    }
}

// --- Get Stats ---
$stats = array(
    'total_appointments' => 0,
    'pending_appointments' => 0,
    'total_orders' => 0,
    'completed_appointments' => 0
);

$stats_query = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'confirmed' THEN 1 ELSE 0 END) as confirmed,
    SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed
    FROM appointments WHERE patient_id = '$patient_id'";
$stats_result = mysqli_query($conn, $stats_query);
if ($stats_result && $row = mysqli_fetch_assoc($stats_result)) {
    $stats['total_appointments'] = $row['total'] ?? 0;
    $stats['pending_appointments'] = $row['pending'] ?? 0;
    $stats['completed_appointments'] = $row['completed'] ?? 0;
}

$orders_count_query = "SELECT COUNT(*) as count FROM orders WHERE patient_id = '$patient_id'";
$orders_count_result = mysqli_query($conn, $orders_count_query);
if ($orders_count_result && $row = mysqli_fetch_assoc($orders_count_result)) {
    $stats['total_orders'] = $row['count'] ?? 0;
}

// --- Helper function for status badge ---
function getStatusBadge($status) {
    $colors = [
        'pending' => 'warning',
        'confirmed' => 'info',
        'completed' => 'success',
        'cancelled' => 'danger',
        'no_show' => 'secondary',
        'processing' => 'primary',
        'shipped' => 'info',
        'delivered' => 'success'
    ];
    $color = $colors[$status] ?? 'secondary';
    $labels = [
        'pending' => 'বিচারাধীন',
        'confirmed' => 'নিশ্চিত',
        'completed' => 'সম্পন্ন',
        'cancelled' => 'বাতিল',
        'no_show' => 'উপস্থিত নয়',
        'processing' => 'প্রক্রিয়াকরণ',
        'shipped' => 'পাঠানো হয়েছে',
        'delivered' => 'পৌঁছেছে'
    ];
    $label = $labels[$status] ?? ucfirst($status);
    return "<span class='badge bg-$color'>$label</span>";
}

// --- Helper function for payment status ---
function getPaymentBadge($status) {
    $colors = [
        'pending' => 'warning',
        'paid' => 'success',
        'failed' => 'danger',
        'refunded' => 'info'
    ];
    $color = $colors[$status] ?? 'secondary';
    $labels = [
        'pending' => 'বিচারাধীন',
        'paid' => 'পরিশোধিত',
        'failed' => 'ব্যর্থ',
        'refunded' => 'ফেরত'
    ];
    $label = $labels[$status] ?? ucfirst($status);
    return "<span class='badge bg-$color'>$label</span>";
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ড্যাশবোর্ড | <?php echo htmlspecialchars($brand['name']); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #2d6a4f;
            --primary-dark: #1b4332;
            --primary-light: #52b788;
            --secondary: #25D366;
            --accent: #f39c12;
            --bg-light: #f8f9fa;
            --text-dark: #1a1a2e;
            --text-light: #6c757d;
            --shadow: 0 10px 40px rgba(0,0,0,0.08);
            --radius: 20px;
            --navbar-height: 70px;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Hind Siliguri', 'SolaimanLipi', Arial, sans-serif;
            background: #f0f4f8;
            color: var(--text-dark);
            padding-top: var(--navbar-height);
            line-height: 1.7;
        }
        
        .container-custom {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        /* NAVBAR */
        .navbar {
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 20px rgba(0,0,0,0.06);
            padding: 8px 0;
            transition: all 0.3s ease;
            height: var(--navbar-height);
            min-height: var(--navbar-height);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }
        .navbar.scrolled {
            background: rgba(255,255,255,0.98);
            box-shadow: 0 4px 30px rgba(0,0,0,0.1);
        }
        .navbar-brand {
            font-weight: 700;
            color: var(--primary) !important;
            font-size: 1.3rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .navbar-brand img {
            height: 40px;
            width: auto;
            object-fit: contain;
        }
        .navbar .nav-link {
            color: #2c3e50;
            font-weight: 500;
            padding: 8px 16px;
            border-radius: 8px;
            transition: all 0.3s ease;
            font-size: 0.95rem;
        }
        .navbar .nav-link:hover,
        .navbar .nav-link.active {
            color: var(--primary);
            background: rgba(45, 106, 79, 0.08);
        }

        .btn-nav {
            padding: 6px 16px;
            border-radius: 50px;
            font-weight: 600;
            font-size: 0.9rem;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }
        .btn-logout {
            background: #e74c3c;
            color: white !important;
        }
        .btn-logout:hover {
            background: #c0392b;
            color: white !important;
            transform: translateY(-2px);
        }
        .btn-appointment {
            background: var(--primary);
            color: white !important;
        }
        .btn-appointment:hover {
            background: var(--primary-dark);
            color: white !important;
            transform: translateY(-2px);
        }

        /* DASHBOARD */
        .dashboard-header {
            background: linear-gradient(135deg, #2d6a4f, #52b788);
            padding: 30px 0 40px;
            color: white;
            border-radius: 0 0 30px 30px;
            margin-bottom: 30px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: -20px 0 30px;
        }
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            text-align: center;
            transition: all 0.3s ease;
        }
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 40px rgba(0,0,0,0.12);
        }
        .stat-card .stat-icon {
            font-size: 2rem;
            color: var(--primary);
            margin-bottom: 5px;
        }
        .stat-card .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: var(--text-dark);
        }
        .stat-card .stat-label {
            color: var(--text-light);
            font-size: 0.9rem;
        }

        .section-card {
            background: white;
            border-radius: var(--radius);
            padding: 25px;
            box-shadow: var(--shadow);
            margin-bottom: 25px;
        }
        .section-card .section-title {
            font-size: 1.2rem;
            font-weight: 700;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .section-card .section-title a {
            font-size: 0.9rem;
            font-weight: 500;
            color: var(--primary);
            text-decoration: none;
        }
        .section-card .section-title a:hover {
            text-decoration: underline;
        }

        .appointment-item, .order-item {
            padding: 12px 0;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        .appointment-item:last-child, .order-item:last-child {
            border-bottom: none;
        }
        .appointment-item .date {
            font-weight: 600;
            color: var(--text-dark);
        }
        .appointment-item .chamber {
            color: var(--text-light);
            font-size: 0.9rem;
        }

        .quick-actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }
        .quick-action {
            background: var(--bg-light);
            padding: 20px;
            border-radius: 15px;
            text-align: center;
            text-decoration: none;
            color: var(--text-dark);
            transition: all 0.3s ease;
        }
        .quick-action:hover {
            background: var(--primary);
            color: white;
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(45, 106, 79, 0.2);
        }
        .quick-action i {
            font-size: 1.8rem;
            display: block;
            margin-bottom: 8px;
        }
        .quick-action:hover i {
            color: white;
        }

        .empty-state {
            text-align: center;
            padding: 30px 20px;
            color: var(--text-light);
        }
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 15px;
            opacity: 0.3;
        }

        @media (max-width: 767px) {
            :root { --navbar-height: 60px; }
            .navbar-collapse {
                background: white;
                padding: 20px;
                border-radius: 16px;
                box-shadow: 0 20px 60px rgba(0,0,0,0.15);
                margin-top: 10px;
                max-height: 80vh;
                overflow-y: auto;
            }
            .navbar .nav-link { padding: 10px 16px; }
            .stats-grid { grid-template-columns: 1fr 1fr; }
            .quick-actions { grid-template-columns: 1fr 1fr; }
            .appointment-item, .order-item {
                flex-direction: column;
                align-items: flex-start;
            }
        }

        @media (max-width: 480px) {
            .stats-grid { grid-template-columns: 1fr; }
            .quick-actions { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

<!-- ============================================
     NAVIGATION
     ============================================ -->
<nav class="navbar navbar-expand-lg fixed-top" id="navbar">
    <div class="container-custom">
        <a class="navbar-brand" href="index.php">
            <?php if (!empty($brand['logo'])): ?>
                <img src="<?php echo htmlspecialchars($brand['logo']); ?>" alt="Logo">
            <?php else: ?>
                <i class="fas fa-clinic-medical"></i>
            <?php endif; ?>
            <span><?php echo htmlspecialchars($brand['name']); ?></span>
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ms-auto">
                <li class="nav-item"><a class="nav-link active" href="dashboard.php"><i class="fas fa-tachometer-alt"></i> ড্যাশবোর্ড</a></li>
                <li class="nav-item"><a class="nav-link" href="book.php"><i class="fas fa-calendar-check"></i> অ্যাপয়েন্টমেন্ট</a></li>
                <li class="nav-item"><a class="nav-link" href="profile.php"><i class="fas fa-user"></i> প্রোফাইল</a></li>
                <li class="nav-item"><a class="btn-nav btn-logout" href="logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a></li>
            </ul>
        </div>
    </div>
</nav>

<!-- ============================================
     DASHBOARD HEADER
     ============================================ -->
<div class="dashboard-header">
    <div class="container-custom">
        <div class="d-flex justify-content-between align-items-center flex-wrap">
            <div>
                <h1 class="mb-0"><i class="fas fa-user-md"></i> স্বাগতম, <?php echo htmlspecialchars($patient_name); ?>!</h1>
                <p class="mb-0 opacity-75">আপনার অ্যাপয়েন্টমেন্ট ও অর্ডার তথ্য</p>
            </div>
            <div>
                <a href="book.php" class="btn btn-light btn-sm">
                    <i class="fas fa-plus-circle"></i> নতুন অ্যাপয়েন্টমেন্ট
                </a>
            </div>
        </div>
    </div>
</div>

<!-- ============================================
     STATS
     ============================================ -->
<div class="container-custom">
    <div class="stats-grid">
        <div class="stat-card" data-aos="fade-up">
            <div class="stat-icon"><i class="fas fa-calendar-check"></i></div>
            <div class="stat-number"><?php echo $stats['total_appointments']; ?></div>
            <div class="stat-label">মোট অ্যাপয়েন্টমেন্ট</div>
        </div>
        <div class="stat-card" data-aos="fade-up" data-aos-delay="100">
            <div class="stat-icon"><i class="fas fa-clock" style="color: #f39c12;"></i></div>
            <div class="stat-number"><?php echo $stats['pending_appointments']; ?></div>
            <div class="stat-label">বিচারাধীন অ্যাপয়েন্টমেন্ট</div>
        </div>
        <div class="stat-card" data-aos="fade-up" data-aos-delay="200">
            <div class="stat-icon"><i class="fas fa-check-circle" style="color: #2ecc71;"></i></div>
            <div class="stat-number"><?php echo $stats['completed_appointments']; ?></div>
            <div class="stat-label">সম্পন্ন অ্যাপয়েন্টমেন্ট</div>
        </div>
        <div class="stat-card" data-aos="fade-up" data-aos-delay="300">
            <div class="stat-icon"><i class="fas fa-shopping-bag" style="color: #3498db;"></i></div>
            <div class="stat-number"><?php echo $stats['total_orders']; ?></div>
            <div class="stat-label">মোট অর্ডার</div>
        </div>
    </div>

    <!-- ============================================
         QUICK ACTIONS
     ============================================ -->
    <div class="section-card" data-aos="fade-up">
        <div class="section-title">
            <span><i class="fas fa-bolt" style="color: #f39c12;"></i> দ্রুত কর্ম</span>
        </div>
        <div class="quick-actions">
            <a href="book.php" class="quick-action">
                <i class="fas fa-calendar-plus"></i>
                <span>নতুন অ্যাপয়েন্টমেন্ট</span>
            </a>
            <a href="profile.php" class="quick-action">
                <i class="fas fa-user-edit"></i>
                <span>প্রোফাইল আপডেট</span>
            </a>
            <a href="../index.php#products" class="quick-action">
                <i class="fas fa-shopping-cart"></i>
                <span>পণ্য অর্ডার</span>
            </a>
            <a href="../index.php#contact" class="quick-action">
                <i class="fas fa-headset"></i>
                <span>সাহায্য</span>
            </a>
        </div>
    </div>

    <!-- ============================================
         RECENT APPOINTMENTS
     ============================================ -->
    <div class="section-card" data-aos="fade-up">
        <div class="section-title">
            <span><i class="fas fa-calendar-check" style="color: var(--primary);"></i> সাম্প্রতিক অ্যাপয়েন্টমেন্ট</span>
            <a href="appointments.php">সব দেখুন →</a>
        </div>
        <?php if (!empty($appointments)): ?>
            <?php foreach ($appointments as $appointment): ?>
                <div class="appointment-item">
                    <div>
                        <span class="date">
                            <?php echo date('d M Y', strtotime($appointment['appointment_date'])); ?>
                        </span>
                        <span class="chamber">
                            <i class="fas fa-hospital"></i> 
                            <?php echo htmlspecialchars($appointment['chamber_name'] ?? 'N/A'); ?>
                        </span>
                    </div>
                    <div>
                        <?php echo getStatusBadge($appointment['status']); ?>
                        <span class="text-muted ms-2">
                            ৳<?php echo number_format($appointment['fee'] ?? 0, 2); ?>
                        </span>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-calendar-times"></i>
                <p>কোনও অ্যাপয়েন্টমেন্ট পাওয়া যায়নি।</p>
                <a href="book.php" class="btn btn-primary btn-sm">নতুন অ্যাপয়েন্টমেন্ট করুন</a>
            </div>
        <?php endif; ?>
    </div>

    <!-- ============================================
         RECENT ORDERS - FIXED
     ============================================ -->
    <div class="section-card" data-aos="fade-up">
        <div class="section-title">
            <span><i class="fas fa-shopping-bag" style="color: var(--primary);"></i> সাম্প্রতিক অর্ডার</span>
            <a href="orders.php">সব দেখুন →</a>
        </div>
        <?php if (!empty($orders)): ?>
            <?php foreach ($orders as $order): ?>
                <div class="order-item">
                    <div>
                        <span class="date">
                            <?php echo htmlspecialchars($order['product_name'] ?? 'পণ্য'); ?>
                        </span>
                        <span class="chamber">
                            <i class="fas fa-calendar-alt"></i> 
                            <?php echo isset($order['created_at']) ? date('d M Y', strtotime($order['created_at'])) : 'N/A'; ?>
                        </span>
                    </div>
                    <div>
                        <?php echo getStatusBadge($order['order_status'] ?? $order['status'] ?? 'pending'); ?>
                        <span class="text-muted ms-2">
                            ৳<?php echo number_format($order['total_amount'] ?? $order['amount'] ?? 0, 2); ?>
                        </span>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-shopping-bag"></i>
                <p>কোনও অর্ডার পাওয়া যায়নি।</p>
                <a href="../index.php#products" class="btn btn-primary btn-sm">পণ্য ব্রাউজ করুন</a>
            </div>
        <?php endif; ?>
    </div>

    <!-- ============================================
         PATIENT INFO
     ============================================ -->
    <div class="section-card" data-aos="fade-up">
        <div class="section-title">
            <span><i class="fas fa-id-card" style="color: var(--primary);"></i> আপনার তথ্য</span>
            <a href="profile.php">আপডেট করুন →</a>
        </div>
        <div class="row g-3">
            <div class="col-md-6">
                <p><strong><i class="fas fa-user"></i> নাম:</strong> <?php echo htmlspecialchars($patient['name'] ?? $patient_name); ?></p>
            </div>
            <div class="col-md-6">
                <p><strong><i class="fas fa-phone"></i> মোবাইল:</strong> <?php echo htmlspecialchars($patient['mobile'] ?? ''); ?></p>
            </div>
            <div class="col-md-6">
                <p><strong><i class="fas fa-envelope"></i> ইমেইল:</strong> <?php echo htmlspecialchars($patient['email'] ?? 'N/A'); ?></p>
            </div>
            <div class="col-md-6">
                <p><strong><i class="fas fa-calendar-alt"></i> জয়েন:</strong> <?php echo isset($patient['created_at']) ? date('d M Y', strtotime($patient['created_at'])) : 'N/A'; ?></p>
            </div>
        </div>
    </div>
</div>

<!-- ============================================
     FOOTER
     ============================================ -->
<footer style="background: #1a1a2e; color: rgba(255,255,255,0.7); padding: 30px 0; text-align: center; margin-top: 40px;">
    <div class="container-custom">
        <p>&copy; <?php echo date('Y'); ?> <?php echo htmlspecialchars($brand['name']); ?> - সর্বস্বত্ব সংরক্ষিত</p>
        <small><?php echo htmlspecialchars($brand['slogan']); ?></small>
    </div>
</footer>

<!-- ============================================
     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 src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script>

<script>
AOS.init({
    duration: 800,
    once: true,
    offset: 50,
    easing: 'ease-out-cubic'
});

$(window).scroll(function() {
    if ($(window).scrollTop() > 50) {
        $('#navbar').addClass('scrolled');
    } else {
        $('#navbar').removeClass('scrolled');
    }
});
</script>

</body>
</html>