/home/awneajlw/public_html/codestechvista.com/search-record.php
<?php
/**
 * Search Record Page - Search and Display Patient Orders
 * This page allows users to search orders by patient name, tracking ID, or phone number
 * Features: Real-time search, filter options, responsive design, pagination
 */

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/currency_helper.php';

// Check if user is logged in
if (!isLoggedIn()) {
    header('Location: welcome.php');
    exit();
}

$search_query = '';
$search_results = [];
$total_results = 0;
$error_message = '';
$current_page = 1;
$records_per_page = 5;
$total_pages = 0;

// Handle search
if (isset($_GET['q']) && !empty(trim($_GET['q']))) {
    $search_query = trim($_GET['q']);
    $current_page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
    
    try {
        $database = new Database();
        $db = $database->getConnection();
        
        $user_id = $_SESSION['user_id'];
        $search_term = '%' . $search_query . '%';
        
        // Check if current user is sub user and get main user ID
        $main_user_id = $user_id;
        $is_sub_user = false;
        
        try {
            $check_user_query = "SELECT user_type, parent_user_id FROM users WHERE id = ?";
            $check_user_stmt = $db->prepare($check_user_query);
            $check_user_stmt->execute([$user_id]);
            $user_info = $check_user_stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user_info && $user_info['user_type'] === 'sub' && $user_info['parent_user_id']) {
                $is_sub_user = true;
                $main_user_id = $user_info['parent_user_id'];
            }
        } catch (Exception $e) {
            // If columns don't exist, treat as main user
            error_log("User type check failed: " . $e->getMessage());
        }
        
        // Get user's currency (use main user's currency for sub users)
        $currency_user_id = $is_sub_user ? $main_user_id : $user_id;
        $user_currency = getUserCurrency($db, $currency_user_id);
        
        // Build user IDs array for search (include both main user and sub users)
        $user_ids = [$user_id]; // Current user's orders
        
        if ($is_sub_user) {
            // If sub user, also include main user's orders
            $user_ids[] = $main_user_id;
        } else {
            // If main user, include all sub users' orders
            try {
                $sub_users_query = "SELECT id FROM users WHERE parent_user_id = ? AND user_type = 'sub'";
                $sub_users_stmt = $db->prepare($sub_users_query);
                $sub_users_stmt->execute([$user_id]);
                $sub_user_ids = $sub_users_stmt->fetchAll(PDO::FETCH_COLUMN);
                $user_ids = array_merge($user_ids, $sub_user_ids);
            } catch (Exception $e) {
                error_log("Error fetching sub users: " . $e->getMessage());
            }
        }
        
        // Create placeholders for IN clause
        $placeholders = str_repeat('?,', count($user_ids) - 1) . '?';
        
        // Search in orders table (include all relevant user IDs)
        $orders_sql = "SELECT o.*, s.shop_name, 'orders' as source_table 
                      FROM orders o 
                      LEFT JOIN shops s ON o.user_id = s.user_id 
                      WHERE o.user_id IN ($placeholders)
                      AND (o.tracking_id LIKE ? 
                            OR o.patient_name LIKE ? 
                            OR o.whatsapp_number LIKE ?)";
        
        $orders_params = array_merge($user_ids, [$search_term, $search_term, $search_term]);
        $stmt1 = $db->prepare($orders_sql);
        $stmt1->execute($orders_params);
        $orders_results = $stmt1->fetchAll(PDO::FETCH_ASSOC);
        
        // Search in add_record table (include all relevant user IDs)
        $add_record_sql = "SELECT a.*, s.shop_name, 'add_record' as source_table 
                          FROM add_record a 
                          LEFT JOIN shops s ON a.user_id = s.user_id 
                          WHERE a.user_id IN ($placeholders)
                          AND (a.tracking_id LIKE ? 
                                OR a.patient_name LIKE ? 
                                OR a.whatsapp_number LIKE ?)";
        
        $add_record_params = array_merge($user_ids, [$search_term, $search_term, $search_term]);
        $stmt2 = $db->prepare($add_record_sql);
        $stmt2->execute($add_record_params);
        $add_record_results = $stmt2->fetchAll(PDO::FETCH_ASSOC);
        
        // Combine results
        $all_results = array_merge($orders_results, $add_record_results);
        
        // Sort by created_at descending
        usort($all_results, function($a, $b) {
            return strtotime($b['created_at']) - strtotime($a['created_at']);
        });
        
        $total_results = count($all_results);
        $total_pages = ceil($total_results / $records_per_page);
        
        // Apply pagination
        $offset = ($current_page - 1) * $records_per_page;
        $search_results = array_slice($all_results, $offset, $records_per_page);
        
    } catch (Exception $e) {
        $error_message = "Search error: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search Record - OPTI SLIP</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/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">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #169D53 0%, #128a43 100%);
            min-height: 100vh;
            padding: 20px;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        .back-btn {
            background: rgba(255, 255, 255, 0.9);
            border: none;
            color: #169D53;
            font-size: 20px;
            cursor: pointer;
            margin-bottom: 30px;
            padding: 12px 16px;
            border-radius: 12px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
        }
        
        .back-btn:hover {
            background: white;
            transform: translateX(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .search-header {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 40px;
            margin-bottom: 40px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            text-align: center;
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .search-title {
            color: #2d3748;
            font-size: 32px;
            font-weight: 800;
            margin-bottom: 15px;
            background: linear-gradient(135deg, #169D53, #128a43);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .search-subtitle {
            color: #718096;
            font-size: 18px;
            margin-bottom: 40px;
            font-weight: 500;
        }
        
        .search-form {
            max-width: 700px;
            margin: 0 auto;
            position: relative;
        }
        
        .search-input-group {
            position: relative;
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }
        
        .search-input-wrapper {
            position: relative;
            flex: 1;
            min-width: 300px;
        }
        
        .search-input {
            width: 100%;
            padding: 18px 25px 18px 55px;
            border: 2px solid #e2e8f0;
            border-radius: 15px;
            font-size: 16px;
            outline: none;
            transition: all 0.3s ease;
            background: white;
            box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        }
        
        .search-input:focus {
            border-color: #169D53;
            box-shadow: 0 0 0 4px rgba(22, 157, 83, 0.1);
            transform: translateY(-2px);
        }
        
        .search-icon {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: #169D53;
            font-size: 20px;
            z-index: 10;
            pointer-events: none;
        }
        
        .search-btn {
            background: linear-gradient(135deg, #169D53 0%, #128a43 100%);
            color: white;
            border: none;
            padding: 18px 35px;
            border-radius: 15px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 8px 25px rgba(22, 157, 83, 0.3);
            white-space: nowrap;
        }
        
        .search-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 12px 35px rgba(22, 157, 83, 0.4);
        }
        
        .search-tips {
            margin-top: 25px;
            color: #718096;
            font-size: 15px;
            background: rgba(22, 157, 83, 0.05);
            padding: 15px 20px;
            border-radius: 10px;
            border-left: 4px solid #169D53;
        }
        
        .results-section {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f7fafc;
        }
        
        .results-title {
            color: #2d3748;
            font-size: 24px;
            font-weight: 700;
        }
        
        .results-count {
            background: linear-gradient(135deg, #169D53, #128a43);
            color: white;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
            box-shadow: 0 4px 15px rgba(22, 157, 83, 0.3);
        }
        
        .no-results {
            text-align: center;
            padding: 80px 20px;
            color: #718096;
        }
        
        .no-results i {
            font-size: 64px;
            color: #cbd5e0;
            margin-bottom: 25px;
        }
        
        .no-results h3 {
            color: #4a5568;
            margin-bottom: 15px;
            font-size: 24px;
            font-weight: 600;
        }
        
        .no-results p {
            font-size: 16px;
            margin-bottom: 10px;
        }
        
        .records-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(600px, 1fr));
            gap: 30px;
            margin-bottom: 40px;
        }
        
        .search-result-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            overflow: hidden;
            transition: all 0.3s ease;
            border: 1px solid #f1f5f9;
        }
        
        .search-result-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(0,0,0,0.15);
        }
        
        .result-header {
            background: linear-gradient(135deg, #169D53 0%, #128a43 100%);
            color: white;
            padding: 25px;
            text-align: center;
            position: relative;
        }
        
        .result-title {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 5px;
        }
        
        .result-subtitle {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .result-content {
            padding: 30px;
        }
        
        .result-row {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 12px 0;
            border-bottom: 1px solid #f7fafc;
            transition: all 0.2s ease;
        }
        
        .result-row:hover {
            background: #f8fafc;
            margin: 0 -15px;
            padding: 12px 15px;
            border-radius: 8px;
        }
        
        .result-row:last-child {
            border-bottom: none;
        }
        
        .result-label {
            font-size: 14px;
            color: #718096;
            font-weight: 600;
            flex: 0 0 140px;
            margin-right: 15px;
            line-height: 1.4;
        }
        
        .result-value {
            font-size: 14px;
            color: #2d3748;
            font-weight: 500;
            text-align: right;
            flex: 1;
            word-wrap: break-word;
            line-height: 1.4;
        }
        
        .special-note-section {
            margin: 25px 0;
            padding: 20px;
            background: #f8fafc;
            border-radius: 12px;
            border-left: 4px solid #169D53;
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 700;
            color: #2d3748;
            margin-bottom: 10px;
        }
        
        .note-text {
            color: #4a5568;
            line-height: 1.6;
            font-size: 14px;
        }
        
        .prescription-section {
            margin: 25px 0;
            padding: 30px 25px 35px 25px;
            background: #f8fafc;
            border-radius: 12px;
        }
        
        .prescription-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
            margin-bottom: 30px;
        }
        
        .eye-section {
            background: white;
            padding: 25px 20px 30px 20px;
            border-radius: 12px;
            border: 1px solid #e2e8f0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .eye-title {
            font-size: 16px;
            font-weight: 700;
            color: #2d3748;
            margin-bottom: 20px;
            text-align: center;
            background: linear-gradient(135deg, #169D53, #128a43);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .prescription-row {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px;
            margin-bottom: 25px;
        }
        
        .prescription-item {
            text-align: center;
            padding: 18px 12px 20px 12px;
            background: #f8fafc;
            border-radius: 10px;
            border: 1px solid #e2e8f0;
        }
        
        .prescription-label {
            font-size: 13px;
            color: #718096;
            margin-bottom: 8px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .prescription-value {
            font-size: 18px;
            font-weight: 700;
            color: #2d3748;
        }
        
        .add-section {
            text-align: center;
            margin-top: 25px;
            padding: 25px 20px 30px 20px;
            background: white;
            border-radius: 10px;
            border: 1px solid #e2e8f0;
        }
        
        .add-value {
            font-size: 20px;
            font-weight: 700;
            color: #169D53;
        }
        
        .action-buttons {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #f1f5f9;
        }
        
        .action-btn {
            background: linear-gradient(135deg, #169D53 0%, #128a43 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
            box-shadow: 0 4px 15px rgba(22, 157, 83, 0.3);
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(22, 157, 83, 0.4);
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 40px;
            padding-top: 30px;
            border-top: 2px solid #f1f5f9;
        }
        
        .pagination-btn {
            background: white;
            border: 2px solid #e2e8f0;
            color: #718096;
            padding: 10px 15px;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 600;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .pagination-btn:hover {
            border-color: #169D53;
            color: #169D53;
            transform: translateY(-2px);
        }
        
        .pagination-btn.active {
            background: linear-gradient(135deg, #169D53, #128a43);
            color: white;
            border-color: transparent;
        }
        
        .pagination-btn.disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .pagination-info {
            color: #718096;
            font-size: 14px;
            font-weight: 500;
        }
        
        .error-message {
            background: linear-gradient(135deg, #fed7d7, #feb2b2);
            color: #742a2a;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 30px;
            border: 1px solid #feb2b2;
            box-shadow: 0 4px 15px rgba(254, 178, 178, 0.3);
        }
        
        /* Mobile Responsive */
        @media (max-width: 768px) {
            body {
                padding: 15px;
            }
            
            .container {
                max-width: 100%;
                padding: 0 15px;
            }
            
            .back-btn {
                font-size: 18px;
                padding: 10px 14px;
                margin-bottom: 20px;
            }
            
            .search-header {
                padding: 25px 20px;
                margin-bottom: 25px;
                border-radius: 15px;
            }
            
            .search-title {
                font-size: 26px;
                margin-bottom: 10px;
            }
            
            .search-subtitle {
                font-size: 16px;
                margin-bottom: 25px;
            }
            
            .search-input-group {
                flex-direction: column;
                gap: 15px;
            }
            
            .search-input-wrapper {
                width: 100%;
            }
            
            .search-input {
                width: 100%;
                padding: 15px 20px 15px 50px;
                font-size: 15px;
            }
            
            .search-icon {
                left: 18px;
                font-size: 18px;
                top: 50%;
                transform: translateY(-50%);
                position: absolute;
                z-index: 10;
                pointer-events: none;
            }
            
            .search-btn {
                width: 100%;
                padding: 15px 25px;
                font-size: 15px;
            }
            
            .search-tips {
                font-size: 13px;
                padding: 12px 15px;
            }
            
            .results-section {
                padding: 20px;
                border-radius: 15px;
            }
            
            .results-header {
                flex-direction: column;
                gap: 15px;
                align-items: flex-start;
            }
            
            .results-title {
                font-size: 20px;
            }
            
            .records-grid {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .search-result-card {
                border-radius: 15px;
            }
            
            .result-header {
                padding: 20px;
            }
            
            .result-title {
                font-size: 18px;
            }
            
            .result-content {
                padding: 20px;
            }
            
            .result-row {
                padding: 10px 0;
            }
            
            .result-label {
                font-size: 13px;
                flex: 0 0 120px;
            }
            
            .result-value {
                font-size: 13px;
            }
            
            .action-buttons {
                flex-direction: column;
                gap: 10px;
                margin-top: 20px;
            }
            
            .action-btn {
                width: 100%;
                justify-content: center;
                padding: 12px 20px;
                font-size: 14px;
            }
            
            .prescription-grid {
                grid-template-columns: 1fr;
                gap: 15px;
            }
            
            .pagination {
                flex-wrap: wrap;
                gap: 8px;
                margin-top: 30px;
            }
            
            .pagination-btn {
                padding: 8px 12px;
                font-size: 13px;
            }
        }
        
        @media (max-width: 480px) {
            body {
                padding: 10px;
            }
            
            .container {
                padding: 0 10px;
            }
            
            .search-header {
                padding: 20px 15px;
                margin-bottom: 20px;
                border-radius: 12px;
            }
            
            .search-title {
                font-size: 22px;
                margin-bottom: 8px;
            }
            
            .search-subtitle {
                font-size: 14px;
                margin-bottom: 20px;
            }
            
            .search-input-wrapper {
                width: 100%;
            }
            
            .search-input {
                width: 100%;
                padding: 12px 15px 12px 45px;
                font-size: 14px;
                border-radius: 12px;
            }
            
            .search-icon {
                left: 15px;
                font-size: 16px;
                top: 50%;
                transform: translateY(-50%);
                position: absolute;
                z-index: 10;
                pointer-events: none;
            }
            
            .search-btn {
                padding: 12px 20px;
                font-size: 14px;
                border-radius: 12px;
            }
            
            .search-tips {
                font-size: 12px;
                padding: 10px 12px;
                margin-top: 15px;
            }
            
            .results-section {
                padding: 15px;
                border-radius: 12px;
            }
            
            .results-title {
                font-size: 18px;
            }
            
            .results-count {
                font-size: 12px;
                padding: 6px 12px;
        }
        
            .result-header {
                padding: 15px;
            }
            
            .result-title {
                font-size: 16px;
            }
            
            .result-content {
                padding: 15px;
            }
            
            .result-row {
                padding: 8px 0;
                flex-direction: column;
                align-items: stretch;
                gap: 5px;
            }
            
            .result-label {
                font-size: 12px;
                flex: none;
                margin-right: 0;
                margin-bottom: 2px;
                font-weight: 700;
                color: #667eea;
            }
            
            .result-value {
                font-size: 13px;
                text-align: left;
                font-weight: 600;
                color: #2d3748;
            }
            
            .action-buttons {
                margin-top: 15px;
                padding-top: 15px;
            }
            
            .action-btn {
                padding: 10px 15px;
                font-size: 13px;
                border-radius: 8px;
            }
            
            .prescription-section {
                margin: 20px 0;
                padding: 15px;
            }
            
            .eye-section {
                padding: 15px;
            }
            
            .prescription-row {
                gap: 10px;
                margin-bottom: 10px;
            }
            
            .prescription-item {
                padding: 8px;
            }
            
            .prescription-label {
                font-size: 11px;
            }
            
            .prescription-value {
                font-size: 14px;
            }
            
            .special-note-section {
                margin: 20px 0;
                padding: 15px;
            }
            
            .pagination {
                margin-top: 25px;
                padding-top: 20px;
            }
            
            .pagination-btn {
                padding: 6px 10px;
                font-size: 12px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <button class="back-btn" onclick="window.location.href='home.php'">
            <i class="fas fa-arrow-left"></i>
        </button>
        
        <div class="search-header">
            <h1 class="search-title">Search Records</h1>
            <p class="search-subtitle">Search patient orders by name, tracking ID, or WhatsApp number</p>
            
            <form class="search-form" method="GET">
                <div class="search-input-group">
                    <div class="search-input-wrapper">
                        <i class="fas fa-search search-icon"></i>
                        <input 
                            type="text" 
                            name="q" 
                            class="search-input" 
                            placeholder="Enter patient name, tracking ID, or phone number..." 
                            value="<?php echo htmlspecialchars($search_query); ?>"
                            required
                        >
                    </div>
                    <button type="submit" class="search-btn">
                        <i class="fas fa-search"></i> Search
                    </button>
                </div>
                <div class="search-tips">
                    <strong>Search Tips:</strong> You can search by patient name, tracking ID (e.g., ORD20241225_1234), or WhatsApp number
                </div>
            </form>
        </div>
        
        <?php if ($error_message): ?>
            <div class="error-message">
                <i class="fas fa-exclamation-triangle"></i>
                <?php echo htmlspecialchars($error_message); ?>
            </div>
        <?php endif; ?>
        
        <?php if ($search_query): ?>
            <div class="results-section">
                <div class="results-header">
                    <h2 class="results-title">Search Results</h2>
                    <span class="results-count"><?php echo $total_results; ?> Found</span>
                </div>
                
                
                <?php if (empty($search_results)): ?>
                    <div class="no-results">
                        <i class="fas fa-search"></i>
                        <h3>No Records Found</h3>
                        <p>No orders found matching "<?php echo htmlspecialchars($search_query); ?>"</p>
                        <p>Try searching with different keywords or check your spelling.</p>
                    </div>
                <?php else: ?>
                    <div class="records-grid">
                    <?php foreach ($search_results as $order): ?>
                        <div class="search-result-card">
                            <div class="result-header">
                                    <h2 class="result-title">Patient Record</h2>
                                    <div class="result-subtitle">Tracking ID: <?php echo htmlspecialchars($order['tracking_id'] ?? 'N/A'); ?></div>
                            </div>
                            
                            <div class="result-content">
                                <div class="result-row">
                                        <span class="result-label">Patient Name</span>
                                    <span class="result-value"><?php echo htmlspecialchars($order['patient_name'] ?? 'N/A'); ?></span>
                                </div>
                                
                                <div class="result-row">
                                        <span class="result-label">WhatsApp Number</span>
                                    <span class="result-value"><?php echo htmlspecialchars($order['whatsapp_number'] ?? 'N/A'); ?></span>
                                </div>
                                
                                <div class="result-row">
                                        <span class="result-label">Frame Detail</span>
                                    <span class="result-value"><?php echo htmlspecialchars($order['frame_detail'] ?? 'N/A'); ?></span>
                                </div>
                                
                                <div class="result-row">
                                        <span class="result-label">Lens Type</span>
                                    <span class="result-value"><?php echo htmlspecialchars($order['lens_type'] ?? 'N/A'); ?></span>
                                </div>
                                
                                <div class="result-row">
                                        <span class="result-label">Booking Date</span>
                                    <span class="result-value"><?php echo $order['created_at'] ? date('d/m/Y', strtotime($order['created_at'])) : 'N/A'; ?></span>
                                </div>
                                
                                <div class="result-row">
                                        <span class="result-label">Delivery Date</span>
                                    <span class="result-value"><?php echo $order['delivery_date'] ? date('d/m/Y', strtotime($order['delivery_date'])) : 'N/A'; ?></span>
                                </div>
                                
                                <div class="result-row">
                                        <span class="result-label">Total Amount</span>
                                    <span class="result-value"><?php echo formatCurrency($order['total_amount'] ?? 0, $user_currency); ?></span>
                                </div>
                                
                                <div class="result-row">
                                        <span class="result-label">Advance Payment</span>
                                    <span class="result-value"><?php echo formatCurrency($order['advance'] ?? 0, $user_currency); ?></span>
                                </div>
                                
                                <div class="result-row">
                                        <span class="result-label">Balance Payment</span>
                                    <span class="result-value"><?php echo formatCurrency($order['balance'] ?? 0, $user_currency); ?></span>
                                </div>
                            </div>
                            
                            <!-- Special Note Section -->
                            <?php if (!empty($order['special_note'])): ?>
                            <div class="special-note-section">
                                <h3 class="section-title">Special Note</h3>
                                <p class="note-text"><?php echo htmlspecialchars($order['special_note']); ?></p>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Prescription Section -->
                            <?php if (isset($order['right_eye_sph']) || isset($order['right_sph']) || isset($order['right_eye_cyl']) || isset($order['right_cyl'])): ?>
                            <div class="prescription-section">
                                <h3 class="section-title">Prescription</h3>
                                
                                <div class="prescription-grid">
                                    <!-- Right Eye -->
                                    <div class="eye-section">
                                        <div class="eye-title">Right Eye</div>
                                        <div class="prescription-row">
                                            <div class="prescription-item">
                                                <div class="prescription-label">SPH</div>
                                                <div class="prescription-value"><?php 
                                                    $sph_value = $order['right_eye_sph'] ?? $order['right_sph'] ?? 0;
                                                    echo ($sph_value > 0 ? '+' : '') . number_format($sph_value, 2);
                                                ?></div>
                                            </div>
                                            <div class="prescription-item">
                                                <div class="prescription-label">CYL</div>
                                                <div class="prescription-value"><?php 
                                                    $cyl_value = $order['right_eye_cyl'] ?? $order['right_cyl'] ?? 0;
                                                    echo ($cyl_value > 0 ? '+' : '') . number_format($cyl_value, 2);
                                                ?></div>
                                            </div>
                                            <div class="prescription-item">
                                                <div class="prescription-label">AXIS</div>
                                                <div class="prescription-value"><?php echo $order['right_eye_axis'] ?? $order['right_axis'] ?? 0; ?></div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Left Eye -->
                                    <div class="eye-section">
                                        <div class="eye-title">Left Eye</div>
                                        <div class="prescription-row">
                                            <div class="prescription-item">
                                                <div class="prescription-label">SPH</div>
                                                <div class="prescription-value"><?php 
                                                    $sph_value = $order['left_eye_sph'] ?? $order['left_sph'] ?? 0;
                                                    echo ($sph_value > 0 ? '+' : '') . number_format($sph_value, 2);
                                                ?></div>
                                            </div>
                                            <div class="prescription-item">
                                                <div class="prescription-label">CYL</div>
                                                <div class="prescription-value"><?php 
                                                    $cyl_value = $order['left_eye_cyl'] ?? $order['left_cyl'] ?? 0;
                                                    echo ($cyl_value > 0 ? '+' : '') . number_format($cyl_value, 2);
                                                ?></div>
                                            </div>
                                            <div class="prescription-item">
                                                <div class="prescription-label">AXIS</div>
                                                <div class="prescription-value"><?php echo $order['left_eye_axis'] ?? $order['left_axis'] ?? 0; ?></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Add Section -->
                                <?php if (isset($order['add_value']) || isset($order['near_add']) || isset($order['add_power'])): ?>
                                <div class="add-section">
                                    <div class="prescription-label">Add</div>
                                    <div class="add-value"><?php 
                                        $add_value = $order['add_value'] ?? $order['near_add'] ?? $order['add_power'] ?? 0;
                                        echo ($add_value > 0 ? '+' : '') . number_format($add_value, 2);
                                    ?></div>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        
                                <!-- Action Buttons -->
                        <div class="action-buttons">
                            <button class="action-btn" onclick="shareOrder(<?php echo $order['id']; ?>)">
                                <i class="fas fa-share-alt"></i>
                                Share
                            </button>
                            <button class="action-btn" onclick="printOrder(<?php echo $order['id']; ?>)">
                                <i class="fas fa-print"></i>
                                Print
                            </button>
                                </div>
                        </div>
                    <?php endforeach; ?>
                    </div>
                    
                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                    <div class="pagination">
                        <?php if ($current_page > 1): ?>
                            <a href="?q=<?php echo urlencode($search_query); ?>&page=1" class="pagination-btn">
                                <i class="fas fa-angle-double-left"></i>
                                First
                            </a>
                            <a href="?q=<?php echo urlencode($search_query); ?>&page=<?php echo $current_page - 1; ?>" class="pagination-btn">
                                <i class="fas fa-angle-left"></i>
                                Previous
                            </a>
                        <?php else: ?>
                            <span class="pagination-btn disabled">
                                <i class="fas fa-angle-double-left"></i>
                                First
                            </span>
                            <span class="pagination-btn disabled">
                                <i class="fas fa-angle-left"></i>
                                Previous
                            </span>
                        <?php endif; ?>
                        
                        <span class="pagination-info">
                            Page <?php echo $current_page; ?> of <?php echo $total_pages; ?>
                        </span>
                        
                        <?php if ($current_page < $total_pages): ?>
                            <a href="?q=<?php echo urlencode($search_query); ?>&page=<?php echo $current_page + 1; ?>" class="pagination-btn">
                                Next
                                <i class="fas fa-angle-right"></i>
                            </a>
                            <a href="?q=<?php echo urlencode($search_query); ?>&page=<?php echo $total_pages; ?>" class="pagination-btn">
                                Last
                                <i class="fas fa-angle-double-right"></i>
                            </a>
                        <?php else: ?>
                            <span class="pagination-btn disabled">
                                Next
                                <i class="fas fa-angle-right"></i>
                            </span>
                            <span class="pagination-btn disabled">
                                Last
                                <i class="fas fa-angle-double-right"></i>
                            </span>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <script>
        function shareOrder(orderId) {
            showNotification('Generating PNG image...', 'info');
            
            // Create a hidden iframe to load the order slip
            const iframe = document.createElement('iframe');
            iframe.style.cssText = `
                position: absolute;
                top: -9999px;
                left: -9999px;
                width: 800px;
                height: 600px;
                border: none;
            `;
            iframe.src = `order-slip.php?id=${orderId}`;
            document.body.appendChild(iframe);
            
            iframe.onload = function() {
                try {
                    // Wait a bit for the content to fully load
                    setTimeout(() => {
                        // Find the main slip card (the white card with patient details)
                        const slipCard = iframe.contentDocument.querySelector('.slip-card, .patient-slip, .main-card, [class*="slip"], [class*="card"]');
                        
                        if (!slipCard) {
                            // If no specific card found, try to find the main content area
                            const mainContent = iframe.contentDocument.querySelector('main, .main-content, .content, .container');
                            if (mainContent) {
                                captureAndShare(mainContent, orderId, iframe);
                            } else {
                                showNotification('Unable to find slip content. Please try again.', 'error');
                                document.body.removeChild(iframe);
                            }
                        } else {
                            captureAndShare(slipCard, orderId, iframe);
                        }
                    }, 2000); // Wait 2 seconds for content to load
                } catch (err) {
                    console.log('Error:', err);
                    showNotification('Unable to generate PNG. Please try again.', 'error');
                    document.body.removeChild(iframe);
                }
            };
            
            iframe.onerror = function() {
                showNotification('Unable to load order slip. Please try again.', 'error');
                document.body.removeChild(iframe);
            };
        }
        
        function captureAndShare(element, orderId, iframe) {
            // Use html2canvas to capture only the specific element
            html2canvas(element, {
                allowTaint: true,
                useCORS: true,
                scale: 2,
                backgroundColor: '#ffffff',
                width: element.offsetWidth,
                height: element.offsetHeight
            }).then(canvas => {
                // Convert canvas to blob
                canvas.toBlob(function(blob) {
                    // Create a file from the blob
                    const file = new File([blob], `patient-slip-${orderId}.png`, { type: 'image/png' });
                    
                    // Try to share the file
                    if (navigator.share && navigator.canShare && navigator.canShare({ files: [file] })) {
                        navigator.share({
                            title: 'OPTI SLIP Patient Record',
                            text: 'Check out this patient record from OPTI SLIP',
                            files: [file]
                        }).then(() => {
                            showNotification('Patient slip shared successfully!', 'success');
                        }).catch(err => {
                            console.log('Share failed:', err);
                            downloadPNG(canvas, orderId);
                        });
                    } else {
                        // Fallback: download the PNG
                        downloadPNG(canvas, orderId);
                    }
                    
                    // Clean up
                    document.body.removeChild(iframe);
                }, 'image/png');
            }).catch(err => {
                console.log('Canvas capture failed:', err);
                showNotification('Unable to generate PNG. Please try again.', 'error');
                document.body.removeChild(iframe);
            });
        }
        
        function downloadPNG(canvas, orderId) {
            // Create download link
            const link = document.createElement('a');
            link.download = `order-slip-${orderId}.png`;
            link.href = canvas.toDataURL('image/png');
            
            // Trigger download
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            showNotification('PNG image downloaded! You can now share it.', 'success');
        }
        
        function printOrder(orderId) {
            // Redirect to order-slip.php with the order ID
            window.open(`order-slip.php?id=${orderId}`, '_blank');
        }
        
        function showNotification(message, type = 'info') {
            // Create notification element
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                padding: 15px 20px;
                border-radius: 8px;
                color: white;
                font-weight: 600;
                z-index: 10000;
                transform: translateX(100%);
                transition: transform 0.3s ease;
                max-width: 300px;
                box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            `;
            
            // Set background color based on type
            const colors = {
                success: '#10b981',
                error: '#ef4444',
                info: '#3b82f6'
            };
            notification.style.backgroundColor = colors[type] || colors.info;
            
            notification.textContent = message;
            document.body.appendChild(notification);
            
            // Animate in
            setTimeout(() => {
                notification.style.transform = 'translateX(0)';
            }, 100);
            
            // Remove after 3 seconds
            setTimeout(() => {
                notification.style.transform = 'translateX(100%)';
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, 3000);
        }
        
        // Auto-focus search input on page load
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.querySelector('.search-input');
            if (searchInput && !searchInput.value) {
                searchInput.focus();
            }
            
            // Add smooth scrolling for pagination
            const paginationLinks = document.querySelectorAll('.pagination-btn');
            paginationLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    if (!this.classList.contains('disabled')) {
                        // Smooth scroll to top
                        window.scrollTo({
                            top: 0,
                            behavior: 'smooth'
                        });
                    }
                });
            });
        });
        
        // Add enter key support for search
        document.addEventListener('DOMContentLoaded', function() {
            const searchInput = document.querySelector('.search-input');
            if (searchInput) {
                searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                        e.preventDefault();
                document.querySelector('.search-form').submit();
                    }
                });
            }
        });
        
        // Add loading state to search button
        document.addEventListener('DOMContentLoaded', function() {
            const searchForm = document.querySelector('.search-form');
            const searchBtn = document.querySelector('.search-btn');
            
            if (searchForm && searchBtn) {
                searchForm.addEventListener('submit', function() {
                    searchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Searching...';
                    searchBtn.disabled = true;
                });
            }
        });
    </script>
</body>
</html>