<?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">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Receipt #<?php echo $sale_id; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; color: #333; }
        .receipt-header { border-bottom: 2px solid #333; padding-bottom: 20px; margin-bottom: 20px; }
        .receipt-footer { border-top: 1px dashed #333; padding-top: 20px; margin-top: 30px; }
        .company-logo { max-height: 80px; }
        .receipt-title { font-size: 1.8rem; font-weight: bold; text-transform: uppercase; }
        
        .table thead th { border-bottom: 2px solid #333; background-color: #f8f9fa; font-size: 0.9rem; }
        .table-bordered td, .table-bordered th { border-color: #dee2e6; }
        
        .bilingual { display: flex; flex-direction: column; line-height: 1.2; }
        .text-ar { font-family: Tahoma, sans-serif; font-size: 0.9em; direction: rtl; }
        
        @media print {
            .no-print { display: none !important; }
            body { padding: 0; margin: 0; background: white; }
            .container { max-width: 100%; width: 100%; padding: 0; }
            .card { border: none !important; box-shadow: none !important; }
        }
    </style>
</head>
<body onload="window.print()">

<div class="container my-4" style="max-width: 800px;">
    <div class="no-print mb-4 text-end">
        <button onclick="window.print()" class="btn btn-primary"><i class="bi bi-printer"></i> Print</button>
        <button onclick="window.close()" class="btn btn-secondary">Close</button>
    </div>

    <div class="card p-4">
        <!-- Header -->
        <div class="receipt-header">
            <div class="row align-items-center">
                <div class="col-8">
                    <div class="d-flex align-items-center">
                        <?php if (!empty($settings['company_logo'])): ?>
                            <img src="<?php echo htmlspecialchars($settings['company_logo']); ?>" alt="Logo" class="company-logo me-3">
                        <?php endif; ?>
                        <div>
                            <h4 class="fw-bold m-0"><?php echo htmlspecialchars($settings['company_name'] ?? 'Pharmacy Name'); ?></h4>
                            <div class="small text-muted mt-1">
                                <?php echo htmlspecialchars($settings['company_address'] ?? ''); ?><br>
                                <?php echo htmlspecialchars($settings['company_phone'] ?? ''); ?>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-4 text-end">
                    <div class="receipt-title">RECEIPT</div>
                    <div class="text-ar">إيصال استلام</div>
                    <div class="mt-2">
                        <strong>#<?php echo str_pad($sale_id, 6, '0', STR_PAD_LEFT); ?></strong>
                    </div>
                    <div class="small text-muted">
                        <?php echo date('d/m/Y h:i A', strtotime($sale['created_at'])); ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Patient Info (if applicable) -->
        <?php if ($sale['patient_id']): ?>
        <div class="row mb-4 border-bottom pb-3">
            <div class="col-12">
                <span class="fw-bold">Patient / المريض:</span>
                <?php echo htmlspecialchars($sale['patient_name']); ?> 
                <?php if($sale['patient_phone']) echo ' (' . htmlspecialchars($sale['patient_phone']) . ')'; ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- Items Table -->
        <table class="table table-bordered mb-4">
            <thead>
                <tr>
                    <th class="text-center" width="50">#</th>
                    <th>
                        <div class="d-flex justify-content-between">
                            <span>Item Description</span>
                            <span class="text-ar">الصنف</span>
                        </div>
                    </th>
                    <th class="text-center" width="80">
                        <div class="d-flex justify-content-between px-1">
                            <span>Qty</span>
                            <span class="text-ar">العدد</span>
                        </div>
                    </th>
                    <th class="text-end" width="120">
                        <div class="d-flex justify-content-between px-1">
                            <span>Price</span>
                            <span class="text-ar">السعر</span>
                        </div>
                    </th>
                    <th class="text-end" width="120">
                        <div class="d-flex justify-content-between px-1">
                            <span>Total</span>
                            <span class="text-ar">الإجمالي</span>
                        </div>
                    </th>
                </tr>
            </thead>
            <tbody>
                <?php $i = 1; foreach ($items as $item): ?>
                <tr>
                    <td class="text-center"><?php echo $i++; ?></td>
                    <td>
                        <div class="fw-bold"><?php echo htmlspecialchars($item['drug_name_en']); ?></div>
                        <?php if($item['drug_name_ar']): ?>
                            <div class="text-ar small text-muted"><?php echo htmlspecialchars($item['drug_name_ar']); ?></div>
                        <?php endif; ?>
                        <?php if($item['sku']): ?>
                            <div class="small text-muted" style="font-size: 0.75rem;">SKU: <?php echo htmlspecialchars($item['sku']); ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="text-center"><?php echo $item['quantity']; ?></td>
                    <td class="text-end"><?php echo format_currency($item['unit_price']); ?></td>
                    <td class="text-end"><?php echo format_currency($item['total_price']); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="4" class="text-end fw-bold">
                        TOTAL / الإجمالي
                    </td>
                    <td class="text-end fw-bold fs-5">
                        <?php echo format_currency($sale['total_amount']); ?>
                    </td>
                </tr>
            </tfoot>
        </table>

        <!-- Payment Info -->
        <div class="row">
            <div class="col-6">
                <div class="small">
                    <strong>Payment Method / طريقة الدفع:</strong><br>
                    <span class="text-uppercase"><?php echo htmlspecialchars($sale['payment_method']); ?></span>
                </div>
            </div>
            <div class="col-6 text-end">
                <!--
                <br>
                <div class="border-top border-dark d-inline-block pt-1" style="width: 200px; text-align: center;">
                    <span class="small">Signature / التوقيع</span>
                </div>
                -->
            </div>
        </div>

        <!-- Footer -->
        <div class="receipt-footer text-center small text-muted">
            <p class="mb-1">Thank you for your visit! / !شكراً لزيارتكم</p>
            <p>Get Well Soon / تمنياتنا بالشفاء العاجل</p>
        </div>
    </div>
</div>

</body>
</html>