<?php
require 'db/config.php';
require 'helpers.php';

require_once __DIR__ . '/includes/auth.php';
check_auth();

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

try {
    $db = db();
    $sale_id = $_GET['sale_id'] ?? 0;

    if (!$sale_id) {
        throw new Exception("Invalid Sale ID");
    }

    // Fetch Sale Details
    $stmt = $db->prepare("
        SELECT 
            s.*, 
            p.name as patient_name,
            p.phone as patient_phone,
            p.civil_id
        FROM pharmacy_sales s
        LEFT JOIN patients p ON s.patient_id = p.id
        WHERE s.id = ?
    ");
    $stmt->execute([$sale_id]);
    $sale = $stmt->fetch();

    if (!$sale) {
        throw new Exception("Sale not found");
    }

    // Fetch Sale Items
    $stmt = $db->prepare("
        SELECT 
            i.*, 
            d.name_en as drug_name_en, 
            d.name_ar as drug_name_ar,
            d.sku
        FROM pharmacy_sale_items i
        JOIN drugs d ON i.drug_id = d.id
        WHERE i.sale_id = ?
    ");
    $stmt->execute([$sale_id]);
    $items = $stmt->fetchAll();

    // Fetch Company Settings (Logo, Address, etc.)
    $stmt = $db->query("SELECT setting_key, setting_value FROM settings");
    $settings = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }

} catch (Exception $e) {
    die("Error: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receipt #<?php echo $sale_id; ?></title>
    <style>
        @media print {
            @page {
                size: 80mm auto; /* Force 80mm width */
                margin: 0;       /* No margins from printer driver */
            }
            html, body {
                width: 80mm;
                margin: 0;
                padding: 0;
            }
            .no-print {
                display: none !important;
            }
            .container {
                width: 100% !important;
                padding: 1mm 2mm !important;
                margin: 0 !important;
            }
        }

        body {
            font-family: 'Courier New', Courier, monospace; /* Monospace for alignment */
            font-size: 11px;
            color: #000;
            background: #fff;
            width: 78mm; /* Screen preview width */
            margin: 0 auto;
            padding: 2mm;
        }

        .container {
            width: 100%;
            box-sizing: border-box;
        }

        .header {
            text-align: center;
            margin-bottom: 5px;
        }
        .logo {
            max-width: 40px;
            max-height: 40px;
            margin-bottom: 2px;
        }
        .company-name {
            font-size: 13px;
            font-weight: bold;
            text-transform: uppercase;
        }
        .company-info {
            font-size: 10px;
            line-height: 1.2;
        }
        .divider {
            border-top: 1px dashed #000;
            margin: 4px 0;
        }
        .receipt-details {
            display: flex;
            justify-content: space-between;
            font-size: 10px;
            margin-bottom: 2px;
        }
        .items-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 10px;
            table-layout: fixed;
        }
        .items-table th {
            text-align: left;
            border-bottom: 1px dashed #000;
            padding: 2px 0;
            font-weight: bold;
        }
        .items-table td {
            padding: 2px 0;
            vertical-align: top;
            word-wrap: break-word;
        }
        
        .ar-text {
            display: block;
            direction: rtl;
            font-family: Tahoma, sans-serif; /* Better for Arabic */
            font-size: 9px;
            color: #333;
        }

        .total-section {
            margin-top: 5px;
            border-top: 1px dashed #000;
            padding-top: 5px;
            font-size: 12px;
        }
        
        .footer {
            text-align: center;
            margin-top: 10px;
            font-size: 10px;
        }
        
        .btn {
            padding: 5px 10px;
            cursor: pointer;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 3px;
            text-decoration: none;
            display: inline-block;
            font-family: sans-serif;
            font-size: 12px;
            margin: 2px;
        }
        .btn-secondary { background: #6c757d; }
        .no-print {
            text-align: center;
            margin-bottom: 10px;
            padding: 10px;
            background: #f8f9fa;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body onload="window.print()">

<div class="no-print">
    <button onclick="window.print()" class="btn">Print 80mm</button>
    <button onclick="window.close()" class="btn btn-secondary">Close</button>
</div>

<div class="container">
    <!-- Header -->
    <div class="header">
        <?php if (!empty($settings['company_logo'])): ?>
            <img src="<?php echo htmlspecialchars($settings['company_logo']); ?>" alt="Logo" class="logo">
        <?php endif; ?>
        <div class="company-name"><?php echo htmlspecialchars($settings['company_name'] ?? 'Pharmacy'); ?></div>
        <div class="company-info">
            <?php echo htmlspecialchars($settings['company_address'] ?? ''); ?><br>
            <?php echo htmlspecialchars($settings['company_phone'] ?? ''); ?>
        </div>
    </div>

    <div class="divider"></div>

    <!-- Receipt Meta -->
    <div class="receipt-details">
        <span>#<?php echo $sale_id; ?></span>
        <span style="direction: ltr;"><?php echo date('Y-m-d H:i', strtotime($sale['created_at'])); ?></span>
    </div>
    <div class="receipt-details">
        <span>رقم الإيصال</span>
        <span>التاريخ</span>
    </div>
    
    <?php if ($sale['patient_id']): ?>
    <div class="divider"></div>
    <div class="receipt-details">
        <span>Patient / المريض:</span>
    </div>
    <div style="font-weight: bold; font-size: 11px;">
        <?php echo htmlspecialchars($sale['patient_name']); ?>
    </div>
    <?php endif; ?>

    <div class="divider"></div>

    <!-- Items -->
    <table class="items-table">
        <thead>
            <tr>
                <th style="width: 45%;">Item / الصنف</th>
                <th style="width: 15%; text-align: center;">Qty<br>العدد</th>
                <th style="width: 20%; text-align: right;">Price<br>السعر</th>
                <th style="width: 20%; text-align: right;">Total<br>الإجمالي</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($items as $item): ?>
            <tr>
                <td>
                    <?php echo htmlspecialchars($item['drug_name_en']); ?>
                    <?php if(!empty($item['drug_name_ar'])): ?>
                        <br><span class="ar-text"><?php echo htmlspecialchars($item['drug_name_ar']); ?></span>
                    <?php endif; ?>
                </td>
                <td style="text-align: center;"><?php echo $item['quantity']; ?></td>
                <td style="text-align: right;"><?php echo number_format($item['unit_price'], 2); ?></td>
                <td style="text-align: right;"><?php echo number_format($item['total_price'], 2); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- Totals -->
    <div class="total-section">
        <div style="display: flex; justify-content: space-between; font-weight: bold; font-size: 13px;">
            <div>TOTAL <span style="font-size: 11px; font-weight: normal;">الإجمالي</span></div>
            <div><?php echo format_currency($sale['total_amount']); ?></div>
        </div>
        <div style="display: flex; justify-content: space-between; margin-top: 5px; font-size: 10px;">
            <div>Paid Via <span style="font-size: 9px;">طريقة الدفع</span></div>
            <div style="text-transform: uppercase;">
                <?php echo htmlspecialchars($sale['payment_method']); ?>
                <?php 
                    $methods_ar = ['cash' => 'نقد', 'card' => 'بطاقة', 'insurance' => 'تأمين'];
                    if(isset($methods_ar[strtolower($sale['payment_method'])])) {
                        echo ' / ' . $methods_ar[strtolower($sale['payment_method'])];
                    }
                ?>
            </div>
        </div>
    </div>

    <div class="divider"></div>

    <!-- Footer -->
    <div class="footer">
        Thank You! / شكراً لكم<br>
        Get Well Soon / بالشفاء العاجل
    </div>
    
    <!-- Cut space -->
    <div style="height: 10mm;"></div>
</div>

</body>
</html>