/home/awneajlw/public_html/codestechvista.com/order-slip.php
<?php
/**
 * Order Slip Page - Display Patient Order Details
 * This page shows the complete order slip for a patient
 * Features: Patient details, prescription info, shop details, action buttons
 */

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();
}

// Get tracking ID from URL (from new order) or order ID (from pending orders)
$tracking_id = isset($_GET['tracking_id']) ? sanitizeInput($_GET['tracking_id']) : '';
$order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$source_table = isset($_GET['source']) ? sanitizeInput($_GET['source']) : 'orders'; 

// Get order details
$order_data = null;
$shop_data = null;

try {
    $database = new Database();
    $db = $database->getConnection();
    
    $user_id = $_SESSION['user_id'];
    
    // 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());
    }
    
    // Build user IDs array for order 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) . '?';
    
    $table_name = ($source_table === 'add_record') ? 'add_record' : 'orders';
    
    // Get order by tracking_id or order_id (search in all relevant user IDs)
    if ($tracking_id) {
        $order_query = "SELECT * FROM $table_name WHERE tracking_id = ? AND user_id IN ($placeholders)";
        $stmt = $db->prepare($order_query);
        $order_params = array_merge([$tracking_id], $user_ids);
        $stmt->execute($order_params);
    } elseif ($order_id) {
        $order_query = "SELECT * FROM $table_name WHERE id = ? AND user_id IN ($placeholders)";
        $stmt = $db->prepare($order_query);
        $order_params = array_merge([$order_id], $user_ids);
        $stmt->execute($order_params);
    } else {
        throw new Exception("No order specified");
    }
    
    $order_data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$order_data) {
        $other_table = ($source_table === 'add_record') ? 'orders' : 'add_record';
        
        if ($tracking_id) {
            $order_query = "SELECT * FROM $other_table WHERE tracking_id = ? AND user_id IN ($placeholders)";
            $stmt = $db->prepare($order_query);
            $order_params = array_merge([$tracking_id], $user_ids);
            $stmt->execute($order_params);
        } elseif ($order_id) {
            $order_query = "SELECT * FROM $other_table WHERE id = ? AND user_id IN ($placeholders)";
            $stmt = $db->prepare($order_query);
            $order_params = array_merge([$order_id], $user_ids);
            $stmt->execute($order_params);
        }
        
        $order_data = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    if (!$order_data) {
        throw new Exception("Order not found");
    }
    
    // Get shop details (use main user's shop for sub users)
    $shop_owner_id = $is_sub_user ? $main_user_id : $user_id;
    $shop_query = "SELECT s.*, u.name as owner_name, u.email 
                   FROM shops s 
                   JOIN users u ON s.user_id = u.id 
                   WHERE s.user_id = ?";
    $stmt = $db->prepare($shop_query);
    $stmt->execute([$shop_owner_id]);
    $shop_data = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // 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);
    
} catch (Exception $e) {
    $error_message = "Error loading order: " . $e->getMessage();
}

// If no order found, redirect to home
if (!$order_data) {
    header('Location: home.php');
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Patient Slip - 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">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: #f5f5f5;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 400px;
            margin: 0 auto;
            padding: 0;
        }
        
        .header-navigation {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 30px;
            padding: 0 10px;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: black;
            font-size: 24px;
            cursor: pointer;
            padding: 10px;
            transition: all 0.3s ease;
            flex: 0 0 auto;
        }
        
        .back-btn:hover {
            color: #169D53;
            transform: translateX(-3px);
        }
        
        .logo-section {
            flex: 0 0 auto;
            text-align: center;
        }
        
        .spacer {
            flex: 0 0 auto;
            width: 44px; /* Same as back button to center logo */
        }
        
        .logo-image {
            width: 150px;
            height: 150px;
            object-fit: contain;
            filter: brightness(0) saturate(100%);
            border-radius: 10px;
        }
        
        .logo-image2 {
            width: 350px;
            height: 350px;
            object-fit: contain;
            filter: brightness(0) saturate(100%);
            border-radius: 10px;
        }
        
        .slip-card {
            position: relative; /* zaroori hai */
            background: white;
            border-radius: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            overflow: hidden;
            margin-bottom: 30px;
        }
        
        .slip-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 30px;
            /*background: linear-gradient(135deg, #169D53, #08371D);*/
            border-radius: 20px 20px 0 0;
            z-index: 1;
        }
        
        /*.watermark-logo-bg {*/
        /*    position: absolute;*/
        /*    top: 50%;*/
        /*    left: 50%;*/
        /*    transform: translate(-50%, -50%);*/
            opacity: 0.05;           /* halka transparent */
            z-index: 1;              /* content ke neeche rahe */
        /*    pointer-events: none;*/
        /*}*/
        
        .logo-image {
            width: 150px;
            height: 150px;
            object-fit: contain;
            filter: brightness(0) saturate(100%);
            border-radius: 10px;
        }
        .watermark-logo-bg {
            position: absolute;
            transform: translate(-50%, -50%);
            top:45%;
            left:50%;
            z-index: 0 !important; 
            /* Isko sab se oopar le aayein */
            pointer-events: none;
            opacity: 0.2;
            /*height:auto;*/
        }
        
        .watermark-logo-bg img {
            max-width:100%;
            top:50% !important;
            /*width: 70%;*/
            height: auto;
            /*color: Red;*/
        }

        .slip-header,
        .slip-content,
        .shop-footer {
            position: relative;
            z-index: 1;
        }
        
        @media print {
            /* Hide header navigation and logo */
            .header-navigation {
                display: none !important;
            }
            
            /* Hide action buttons - multiple selectors to ensure hiding */
            .action-buttons,
            .action-btn,
            button[onclick*="downloadSlip"],
            button[onclick*="printSlip"],
            button[onclick*="shareSlip"] {
                display: none !important;
                visibility: hidden !important;
            }
            
            /* Hide back button */
            .back-btn {
                display: none !important;
            }
            
            /* Show watermark for print */
            .watermark-logo-bg {
                display: block !important;
                opacity: 0.05 !important;
                background-size: contain !important;
            }
        
            /* Make sure print keeps colors */
            * {
                -webkit-print-color-adjust: exact !important;
                color-adjust: exact !important;
            }
            
            /* Ensure proper margins for print */
            body {
                margin: 0 !important;
                padding: 10px !important;
            }
            
            .container {
                margin: 0 !important;
                padding: 0 !important;
            }
        }
        
        
        /*.watermark-logo-bg { background: none; }*/
        /*.watermark-img {*/
        /*    width: 100%;*/
        /*    height: 100%;*/
        /*    object-fit: contain;*/
        /*    opacity: 0.08;*/
        /*    display: block;*/
        /*    pointer-events: none;*/
        /*}*/
        
        .slip-header {
            text-align: center;
            padding: 40px 20px 20px 20px;
            /*border-bottom: 2px solid #f0f0f0;*/
            position: relative;
            z-index: 2;
        }
        
        .slip-title {
            color: #169D53;
            font-size: 22px;
            font-weight: 700;
            margin-bottom: 0;
        }
        
        .slip-content {
            padding: 25px;
            position: relative;
        }
        
        .slip-row {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            padding: 8px 0;
            /*border-bottom: 1px solid #f0f0f0;*/
            min-height: 35px;
        }
        
        .slip-row:last-child {
            border-bottom: none;
        }
        
        .slip-label {
            font-size: 14px;
            color: #666;
            font-weight: 500;
            flex: 0 0 auto;
            margin-right: 10px;
            line-height: 1.4;
        }
        
        .slip-value {
            font-size: 14px;
            color: #333;
            font-weight: 500;
            text-align: left;
            flex: 1;
            word-wrap: break-word;
            line-height: 1.4;
        }
        
        .shop-footer {
            background: linear-gradient(135deg, #169D53, #08371D);
            color: white;
            padding: 20px;
            text-align: left;
        }
        
        .shop-info {
            margin-bottom: 15px;
        }
        
        .shop-name {
            font-size: 18px;
            font-weight: 700;
            margin: 0 0 8px 0;
            color: white;
        }
        
        .shop-address {
            font-size: 13px;
            margin: 0;
            color: rgba(255, 255, 255, 0.9);
            line-height: 1.4;
        }
        
        .social-contacts {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: center;
        }
        
        .contact-item {
            display: flex;
            align-items: center;
            gap: 8px;
            background: rgba(255, 255, 255, 0.1);
            padding: 8px 12px;
            border-radius: 20px;
            font-size: 12px;
            color: white;
            transition: all 0.3s ease;
        }
        
        .contact-item:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-1px);
        }
        
        .contact-item i {
            font-size: 14px;
            width: 16px;
            text-align: center;
        }
        
        .contact-item span {
            font-weight: 500;
        }
        
        .action-buttons {
            display: flex;
            /*flex-wrap: wrap;*/
            gap: 10px;
            padding: 15px;
            justify-content: center;
            grid-template-columns: repeat(3, 1fr);
            
        }
        
        .action-btn {
            background: #169D53;
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 25px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .action-btn:hover {
            background: #128a43;
            color: white;
            transform: translateY(-2px);
        }
        
        .action-btn.secondary {
            background: #169D53;
        }
        
        .action-btn.secondary:hover {
            background: #128a43;
        }
        
        
        
        /*.slip-content {*/
        /*    position: relative;*/
            z-index: 2;
        }
        
        /* Print Styles - A4 Size Optimized */
        @media print {
            * {
                -webkit-print-color-adjust: exact !important;
                color-adjust: exact !important;
            }
            
            body {
                background: white !important;
                padding: 10mm !important;
                margin: 0 !important;
                font-size: 12pt !important;
                line-height: 1.4 !important;
            }
            
            .container {
                max-width: 100% !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            
            .slip-container, .slip-card {
                box-shadow: none !important;
                border: 2px solid #169D53 !important;
                border-radius: 8px !important;
                page-break-inside: avoid !important;
                margin: 0 !important;
                background: white !important;
            }
            
            .slip-header {
                background: #169D53 !important;
                color: white !important;
                padding: 15px !important;
                border-radius: 6px 6px 0 0 !important;
            }
            
            .slip-header h2 {
                font-size: 18pt !important;
                margin: 0 !important;
                color: white !important;
            }
            
            .slip-content {
                padding: 15px !important;
            }
            
            .slip-row {
                padding: 8px 0 !important;
                border-bottom: 1px solid #eee !important;
                display: flex !important;
                justify-content: space-between !important;
            }
            
            .slip-label {
                font-size: 11pt !important;
                color: #333 !important;
                font-weight: 600 !important;
            }
            
            .slip-value {
                font-size: 11pt !important;
                color: #000 !important;
                font-weight: 700 !important;
            }
            
            .shop-footer {
                background: linear-gradient(135deg, #169D53, #08371D) !important;
                color: white !important;
                padding: 15px !important;
                border-radius: 0 0 6px 6px !important;
                text-align: left !important;
            }
            
            .shop-info {
                margin-bottom: 10px !important;
            }
            
            .shop-name {
                color: white !important;
                font-size: 14pt !important;
                margin: 0 0 5px 0 !important;
                font-weight: 700 !important;
            }
            
            .shop-address {
                font-size: 10pt !important;
                color: rgba(255, 255, 255, 0.9) !important;
                margin: 0 !important;
            }
            
            .social-contacts {
                display: flex !important;
                flex-wrap: wrap !important;
                gap: 8px !important;
            }
            
            .contact-item {
                background: rgba(255, 255, 255, 0.2) !important;
                padding: 4px 8px !important;
                border-radius: 12px !important;
                font-size: 9pt !important;
                color: white !important;
                display: flex !important;
                align-items: center !important;
                gap: 4px !important;
            }
            
            .contact-item i {
                font-size: 10pt !important;
                width: 12px !important;
                color: white !important;
            }
            
            .logo-image {
                width: 80px !important;
                height: 80px !important;
                filter: brightness(0) saturate(100%) !important;
                border-radius: 8px !important;
            }
            
            .watermark,
            .back-btn {
                display: none !important;
            }
            
            @page {
                size: A4;
                margin: 15mm;
            }
        }
        
        /* Mobile Responsive - Exact First Image Layout */
        @media (max-width: 768px) {
            body {
                padding: 15px;
                background: #f5f5f5;
            }
            
            .container {
                max-width: 100%;
                padding: 0 10px;
            }
            
            .header-navigation {
                margin-bottom: 20px;
                padding: 0 5px;
            }
            
            .back-btn {
                font-size: 20px;
                padding: 8px;
            }
            
            .spacer {
                width: 36px;
            }
            
            .slip-card {
                margin: 0 auto;
                border-radius: 15px;
                overflow: hidden;
                box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            }
            
            .logo-image {
                width: 100px;
                height: 100px;
            }
            
            /*.watermark-logo-bg {*/
            /*    width: 160px;*/
            /*    height: 160px;*/
            /*    opacity: 0.10;*/
            /*}*/
            
            .slip-header {
                padding: 30px 15px 15px 15px;
            }
            
            .slip-content {
                padding: 20px;
            }
            
            .slip-row {
                padding: 8px 0;
                /*border-bottom: 1px solid #f0f0f0;*/
                display: block;
                justify-content: space-between;
                /*align-items: flex-start;*/
                min-height: 30px;
            }
            
            .slip-label {
                font-size: 13px;
                color: #666;
                font-weight: 500;
                flex: 0 0 auto;
                margin-right: 10px;
                min-width: 120px;
            }
            
            .slip-value {
                font-size: 13px;
                font-weight: 500;
                color: #333;
                text-align: left;
                flex: 1;
                word-break: break-word;
            }
            
            .slip-header h2 {
                font-size: 18px;
                margin-bottom: 10px;
            }
            
            .action-buttons {
                grid-template-columns: repeat(3, 1fr) !important;
                gap: 10px;
                margin-top: 20px;
                display: grid !important; 
            }
            
            .action-btn {
                width: 100%;
                justify-content: center;
                padding: 12px 20px;
                font-size: 14px;
                border-radius: 8px;
            }
            
            .back-btn {
                top: 10px;
                left: 10px;
                font-size: 18px;
                padding: 8px;
                width: 36px;
                height: 36px;
                border-radius: 50%;
                background: rgba(0,0,0,0.1);
                display: flex;
                align-items: center;
                justify-content: center;
            }
            
            .watermark-logo-bg {
                opacity: 0.15 !important;
                width: 250px !important;
                height: 250px !important;
                filter: grayscale(50%) brightness(1.1) !important;
            }
        }
        
        @media (max-width: 480px) {
            body {
                padding: 10px;
            }
            
            .container {
                padding: 0 5px;
            }
            
            .slip-content {
                padding: 15px;
            }
            
            .slip-row {
                padding: 6px 0;
                flex-direction: column;
                align-items: stretch;
                gap: 2px;
                min-height: auto;
            }
            
            .slip-label {
                font-size: 13px;
                margin-right: 0;
                text-align: left;
                min-width: auto;
                margin-bottom: 2px;
            }
            
            .slip-value {
                font-size: 13px;
                text-align: left;
                font-weight: 700;
                color: #000;
            }
            
            .shop-footer {
                padding: 15px;
            }
            
            .shop-name {
                font-size: 15px;
                text-align:left;
            }
            
            .shop-address {
                font-size: 11px;
                text-align:left;
            }
            
            .social-contacts {
                gap: 8px;
                flex-direction: column 2f;
                align-items: flex-left;
                
            }
            
            .contact-item {
                font-size: 11px;
            }
            
            .action-buttons {
                flex-direction: column;
                gap: 8px;
                padding: 10px;
            }
            
            .action-btn {
                width: 100%;
                padding: 12px;
            }
            
            .slip-label {
                font-size: 13px;
            }
            
            .slip-value {
                font-size: 13px;
            }
            
            .slip-header h2 {
                font-size: 16px;
            }
            
            .logo-image {
                width: 80px;
                height: 80px;
            }
            
            .shop-footer {
                padding: 15px;
                text-align: center;
            }
            
            .shop-info {
                margin-bottom: 12px;
            }
            
            .shop-name {
                font-size: 16px;
                margin-bottom: 6px;
            }
            
            .shop-address {
                font-size: 12px;
            }
            
            .social-contacts {
                justify-content: left;
                gap: 10px;
            }
            
            .contact-item {
                padding: 6px 10px;
                font-size: 11px;
                border-radius: 15px;
            }
            
            .contact-item i {
                font-size: 12px;
                width: 14px;
            }
            
            .action-buttons {
                padding: 12px;
                
            }
            
            .action-btn {
                padding: 10px 15px;
                font-size: 13px;
            }
            
            .back-btn {
                width: 32px;
                height: 32px;
                font-size: 16px;
            }
            
            .watermark {
                font-size: 50px;
                opacity: 0.02;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header-navigation">
            <button class="back-btn" onclick="window.location.href='home.php'">
                <i class="fas fa-arrow-left"></i>
            </button>
            
            <div class="logo-section">
                <img src="assets/images/Optislipimage.png" alt="Opti Slip Logo" class="logo-image" onerror="this.style.display='none'; this.parentElement.innerHTML='<div style=\'color: black; font-size: 24px; font-weight: bold; line-height: 1.2; text-align: center;\'>OPTI<br>SLIP</div>'">
                
            </div>
            
            <div class="spacer"></div>
        </div>
        
        
        
        <div class="slip-card">
            <div class="watermark-logo-bg">
                <img src="assets/images/Optislipimage.png" alt="Opti Slip Logo" class="logo-image2" onerror="this.style.display='none'; this.parentElement.innerHTML='<div style=\'color: black; font-size: 24px; font-weight: bold;line-height: 1.2; text-align: center;\'>OPTI<br>SLIP</div>'">
                
                <!--<img src="assets/images/optislipimage2.png" alt="Watermark Logo" class="watermark-img" >-->
            </div>

            
            <div class="slip-header">
                <h2 class="slip-title">Patient Slip</h2>
            </div>
            
            <div class="slip-content">
                <div class="slip-row">
                    <span class="slip-label">Tracking Id :</span>
                    <span class="slip-value"><?php echo htmlspecialchars($order_data['tracking_id'] ?? 'N/A'); ?></span>
                </div>
                
                <div class="slip-row">
                    <span class="slip-label">Description :</span>
                    <span class="slip-value"><?php 
                        $frame_detail = $order_data['frame_detail'] ?? '';
                        $lens_type = $order_data['lens_type'] ?? '';
                        
                        $description_parts = [];
                        if (!empty($frame_detail)) {
                            $description_parts[] = $frame_detail;
                        }
                        if (!empty($lens_type)) {
                            $description_parts[] = $lens_type;
                        }
                        
                        $description = !empty($description_parts) ? implode(' + ', $description_parts) : 'N/A';
                        echo htmlspecialchars($description);
                    ?></span>
                </div>
                
                <div class="slip-row">
                    <span class="slip-label">Patient Name :</span>
                    <span class="slip-value"><?php echo htmlspecialchars($order_data['patient_name'] ?? 'N/A'); ?></span>
                </div>
                
                <div class="slip-row">
                    <span class="slip-label">Booking Date :</span>
                    <span class="slip-value"><?php echo $order_data['created_at'] ? date('d/m/Y', strtotime($order_data['created_at'])) : 'N/A'; ?></span>
                </div>
                
                <div class="slip-row">
                    <span class="slip-label">Delivery Date :</span>
                    <span class="slip-value"><?php echo $order_data['delivery_date'] ? date('d/m/Y', strtotime($order_data['delivery_date'])) : 'N/A'; ?></span>
                </div>
                
                <div class="slip-row">
                    <span class="slip-label">Total Amount :</span>
                    <span class="slip-value"><?php echo formatCurrency($order_data['total_amount'] ?? 0, $user_currency); ?></span>
                </div>
                
                <div class="slip-row">
                    <span class="slip-label">Advance Payment :</span>
                    <span class="slip-value"><?php echo formatCurrency($order_data['advance'] ?? 0, $user_currency); ?></span>
                </div>
                
                <div class="slip-row">
                    <span class="slip-label">Balance Payment :</span>
                    <span class="slip-value"><?php echo formatCurrency($order_data['balance'] ?? 0, $user_currency); ?></span>
                </div>
            </div>
            
            <div class="shop-footer">
                <div class="shop-info">
                    <h4 class="shop-name"><?php echo htmlspecialchars($shop_data['shop_name'] ?? 'Shop Name'); ?></h4>
                    <p class="shop-address">Address: <?php echo htmlspecialchars($shop_data['address'] ?? $shop_data['shop_address'] ?? '95176 Gloria Ranch'); ?></p>
                </div>
                
                <div class="social-contacts">
                    <?php if (!empty($shop_data['shop_whatsapp'])): ?>
                        <div class="contact-item">
                            <i class="fab fa-whatsapp"></i>
                            <span><?php echo htmlspecialchars($shop_data['shop_whatsapp']); ?></span>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($shop_data['shop_facebook'])): ?>
                        <div class="contact-item">
                            <i class="fab fa-facebook"></i>
                            <span><?php echo htmlspecialchars($shop_data['shop_facebook']); ?></span>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($shop_data['shop_instagram'])): ?>
                        <div class="contact-item">
                            <i class="fab fa-instagram"></i>
                            <span><?php echo htmlspecialchars($shop_data['shop_instagram']); ?></span>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($shop_data['website']) || !empty($shop_data['shop_website'])): ?>
                        <div class="contact-item">
                            <i class="fas fa-globe"></i>
                            <span><?php 
                                $website = $shop_data['website'] ?? $shop_data['shop_website'] ?? '';
                                echo htmlspecialchars($website); 
                            ?></span>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="action-buttons">
            <button class="action-btn" onclick="downloadSlip()">
                <i class="fas fa-download"></i>
                Download
            </button>
            <button class="action-btn secondary" onclick="printSlip()">
                <i class="fas fa-print"></i>
                Print
            </button>
            <button class="action-btn" onclick="shareSlip()">
                <i class="fas fa-share"></i>
                Share
            </button>
        </div>
    </div>
    
    <!-- Load html2canvas library for image capture -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    
    <script>
        // Check if watermark image path is correct
        document.addEventListener('DOMContentLoaded', function() {
            const watermarkImg = document.querySelector('.watermark-img');
            if (watermarkImg) {
                console.log('Watermark image element found');
                console.log('Image src:', watermarkImg.src);
                console.log('Full URL:', watermarkImg.src);
                
                // Test image load
                const testImg = new Image();
                testImg.onload = function() {
                    console.log('✅ Image loads successfully from:', this.src);
                };
                testImg.onerror = function() {
                    console.log('❌ Image failed to load from:', this.src);
                };
                testImg.src = watermarkImg.src;
            }
        });
        
        // Download as Image Function
        function downloadSlip() {
            captureAndDownload();
        }
        
        function captureAndDownload() {
            const slipContainer = document.querySelector('.slip-container') || document.querySelector('.slip-card');
            const watermark = document.querySelector('.watermark');
            const actionButtons = document.querySelector('.action-buttons');
            const backBtn = document.querySelector('.back-btn');
            
            // Hide elements for clean capture
            if (watermark) watermark.style.display = 'none';
            if (actionButtons) actionButtons.style.display = 'none';
            if (backBtn) backBtn.style.display = 'none';
            
            // Configure html2canvas options for download
            const options = {
                backgroundColor: '#ffffff',
                scale: 2, // Higher quality
                useCORS: true,
                allowTaint: false,
                scrollX: 0,
                scrollY: 0,
                width: slipContainer.scrollWidth,
                height: slipContainer.scrollHeight,
                windowWidth: slipContainer.scrollWidth,
                windowHeight: slipContainer.scrollHeight,
                x: 0,
                y: 0,
                onclone: function(clonedDoc) {
                    // Ensure styles are applied in cloned document
                    const clonedContainer = clonedDoc.querySelector('.slip-container') || clonedDoc.querySelector('.slip-card');
                    if (clonedContainer) {
                        clonedContainer.style.transform = 'none';
                        clonedContainer.style.position = 'static';
                        clonedContainer.style.overflow = 'visible';
                        clonedContainer.style.height = 'auto';
                        clonedContainer.style.maxHeight = 'none';
                        
                        // Ensure all child elements are visible
                        const allElements = clonedContainer.querySelectorAll('*');
                        allElements.forEach(el => {
                            el.style.visibility = 'visible';
                            el.style.opacity = '1';
                        });
                    }
                }
            };
            
            html2canvas(slipContainer, options).then(canvas => {
                // Create download link
                const link = document.createElement('a');
                link.download = 'patient-slip-<?php echo htmlspecialchars($order_data['tracking_id'] ?? 'order'); ?>.png';
                link.href = canvas.toDataURL('image/png', 0.95);
                link.click();
                
                // Restore hidden elements
                setTimeout(() => {
                    if (watermark) watermark.style.display = '';
                    if (actionButtons) actionButtons.style.display = '';
                    if (backBtn) backBtn.style.display = '';
                }, 500);
            }).catch(error => {
                console.error('Download failed:', error);
                alert('Download failed. Please try again.');
                
                // Restore hidden elements on error
                if (watermark) watermark.style.display = '';
                if (actionButtons) actionButtons.style.display = '';
                if (backBtn) backBtn.style.display = '';
            });
        }
        
        // Print Function - Optimized for A4
        function printSlip() {
            // Set page title for print
            const originalTitle = document.title;
            document.title = 'Patient Slip - <?php echo htmlspecialchars($order_data['tracking_id'] ?? 'Order'); ?>';
            
            // Trigger print
            window.print();
            
            // Restore original title
            setTimeout(() => {
                document.title = originalTitle;
            }, 1000);
        }
        
        // Share as Screenshot Function
        function shareSlip() {
            captureAndShare();
        }
        
        function captureAndShare() {
            const slipContainer = document.querySelector('.slip-container') || document.querySelector('.slip-card');
            const watermark = document.querySelector('.watermark');
            const actionButtons = document.querySelector('.action-buttons');
            const backBtn = document.querySelector('.back-btn');
            
            // Hide elements for clean capture
            if (watermark) watermark.style.display = 'none';
            if (actionButtons) actionButtons.style.display = 'none';
            if (backBtn) backBtn.style.display = 'none';
            
            // Configure html2canvas options for sharing
            const options = {
                backgroundColor: '#ffffff',
                scale: 2, // Higher quality
                useCORS: true,
                allowTaint: false,
                scrollX: 0,
                scrollY: 0,
                width: slipContainer.scrollWidth,
                height: slipContainer.scrollHeight,
                windowWidth: slipContainer.scrollWidth,
                windowHeight: slipContainer.scrollHeight,
                x: 0,
                y: 0,
                onclone: function(clonedDoc) {
                    // Ensure styles are applied in cloned document
                    const clonedContainer = clonedDoc.querySelector('.slip-container') || clonedDoc.querySelector('.slip-card');
                    if (clonedContainer) {
                        clonedContainer.style.transform = 'none';
                        clonedContainer.style.position = 'static';
                        clonedContainer.style.overflow = 'visible';
                        clonedContainer.style.height = 'auto';
                        clonedContainer.style.maxHeight = 'none';
                        clonedContainer.style.width = 'auto';
                        clonedContainer.style.maxWidth = 'none';
                        
                        // Ensure all child elements are visible and properly sized
                        const allElements = clonedContainer.querySelectorAll('*');
                        allElements.forEach(el => {
                            el.style.visibility = 'visible';
                            el.style.opacity = '1';
                            el.style.overflow = 'visible';
                        });
                        
                        // Specifically handle shop footer
                        const shopFooter = clonedContainer.querySelector('.shop-footer');
                        if (shopFooter) {
                            shopFooter.style.display = 'block';
                            shopFooter.style.visibility = 'visible';
                        }
                    }
                }
            };
            
            html2canvas(slipContainer, options).then(canvas => {
                canvas.toBlob(blob => {
                    if (navigator.share && navigator.canShare) {
                        // Try to share with file
                        try {
                            const file = new File([blob], 'patient-slip-<?php echo htmlspecialchars($order_data['tracking_id'] ?? 'order'); ?>.png', { type: 'image/png' });
                            
                            if (navigator.canShare({ files: [file] })) {
                                navigator.share({
                                    title: 'Patient Slip - <?php echo htmlspecialchars($order_data['patient_name'] ?? 'Patient'); ?>',
                                    text: 'Order details for tracking ID: <?php echo htmlspecialchars($order_data['tracking_id'] ?? 'N/A'); ?>',
                                    files: [file]
                                }).catch(error => {
                                    console.error('Share failed:', error);
                                    fallbackShare(canvas);
                                });
                            } else {
                                fallbackShare(canvas);
                            }
                        } catch (error) {
                            console.error('File share not supported:', error);
                            fallbackShare(canvas);
                        }
                    } else {
                        fallbackShare(canvas);
                    }
                    
                    // Restore hidden elements
                    setTimeout(() => {
                        if (watermark) watermark.style.display = '';
                        if (actionButtons) actionButtons.style.display = '';
                        if (backBtn) backBtn.style.display = '';
                    }, 500);
                }, 'image/png', 0.95);
            }).catch(error => {
                console.error('Screenshot capture failed:', error);
                alert('Screenshot capture failed. Please try again.');
                
                // Restore hidden elements on error
                if (watermark) watermark.style.display = '';
                if (actionButtons) actionButtons.style.display = '';
                if (backBtn) backBtn.style.display = '';
            });
        }
        
        function fallbackShare(canvas) {
            // Create a temporary link for download as fallback
            const link = document.createElement('a');
            link.download = 'patient-slip-<?php echo htmlspecialchars($order_data['tracking_id'] ?? 'order'); ?>.png';
            link.href = canvas.toDataURL('image/png', 0.95);
            
            // Show options to user
            const userChoice = confirm('Native sharing not available. Would you like to download the image instead?\\n\\nClick OK to download or Cancel to copy link to clipboard.');
            
            if (userChoice) {
                link.click();
            } else {
                // Copy URL to clipboard as final fallback
                navigator.clipboard.writeText(window.location.href).then(() => {
                    alert('Order slip link copied to clipboard!');
                }).catch(() => {
                    alert('Unable to copy link. Please share this URL manually:\\n' + window.location.href);
                });
            }
        }
    </script>
</body>
</html>