<?php
/**
 * sale_view.php
 * Premium Detailed View for Sales Invoices
 * Features: Invoice Breakdown, Payment Status, Printing, Professional Layout, PDF Export
 */

require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

date_default_timezone_set('Asia/Beirut');

// --- إعدادات اللغة ---
if (session_status() === PHP_SESSION_NONE) session_start();
$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'ar');
if (isset($_GET['lang'])) { $_SESSION['lang'] = $_GET['lang'] === 'ar' ? 'ar' : 'en'; $lang = $_SESSION['lang']; }
$is_ar = $lang === 'ar';
$dir = $is_ar ? 'rtl' : 'ltr';

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

// جلب معرف الفاتورة
$sale_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($sale_id <= 0) {
    header('Location: sales_list.php');
    exit;
}

// --- الترجمة ---
$T = [
    'en' => [
        'title' => 'Sales Invoice',
        'invoice_no' => 'Invoice No.',
        'date' => 'Invoice Date',
        'customer' => 'Bill To',
        'status' => 'Payment Status',
        'item' => 'Product Name',
        'sku' => 'SKU',
        'qty' => 'Qty',
        'price' => 'Unit Price',
        'total' => 'Subtotal',
        'summary' => 'Financial Summary',
        'net_total' => 'Grand Total',
        'paid' => 'Amount Paid',
        'due' => 'Balance Due',
        'tax' => 'Tax',
        'discount' => 'Total Discount',
        'print' => 'Print',
        'pdf' => 'Download PDF',
        'back' => 'Back',
        'paid_status' => 'Paid in Full',
        'partial_status' => 'Partial / Debt',
        'cash' => 'Cash Payment',
        'debt' => 'On Account / Debt'
    ],
    'ar' => [
        'title' => 'فاتورة مبيعات',
        'invoice_no' => 'رقم الفاتورة',
        'date' => 'تاريخ الفاتورة',
        'customer' => 'محررة إلى (العميل)',
        'status' => 'حالة الدفع',
        'item' => 'الصنف / المنتج',
        'sku' => 'باركود',
        'qty' => 'الكمية',
        'price' => 'سعر الوحدة',
        'total' => 'الإجمالي الفرعي',
        'summary' => 'ملخص الحساب المالي',
        'net_total' => 'الإجمالي النهائي',
        'paid' => 'المبلغ المدفوع',
        'due' => 'المتبقي (ديون)',
        'tax' => 'قيمة الضريبة',
        'discount' => 'إجمالي الخصم',
        'print' => 'طباعة',
        'pdf' => 'تحميل PDF',
        'back' => 'رجوع',
        'paid_status' => 'مدفوعة بالكامل',
        'partial_status' => 'آجل / متبقي ذمة',
        'cash' => 'دفع نقدي (كاش)',
        'debt' => 'ذمة (آجل)'
    ]
];
$t = $T[$lang];

// 1. جلب بيانات الفاتورة الأساسية مع بيانات العميل
$stmt = $pdo->prepare("SELECT s.*, c.name as customer_name, c.phone as customer_phone 
                        FROM sales s 
                        LEFT JOIN customers c ON s.customer_id = c.id 
                        WHERE s.id = ? LIMIT 1");
$stmt->execute([$sale_id]);
$sale = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$sale) {
    die($is_ar ? "الفاتورة المطلوبة غير موجودة." : "Invoice not found.");
}

// 2. جلب الأصناف المباعة في هذه الفاتورة
$cols = $pdo->query("SHOW COLUMNS FROM products")->fetchAll(PDO::FETCH_COLUMN);
$nameField = in_array('name_en', $cols) ? 'name_en' : (in_array('name_ar',$cols) ? 'name_ar' : 'name');

$stmt_items = $pdo->prepare("SELECT si.*, p.sku, p.$nameField as product_name 
                              FROM sale_items si 
                              JOIN products p ON si.product_id = p.id 
                              WHERE si.sale_id = ?");
$stmt_items->execute([$sale_id]);
$items = $stmt_items->fetchAll(PDO::FETCH_ASSOC);

// حساب المتبقي والحالة
$remaining = max(0, $sale['total'] - $sale['paid']);
$is_paid_full = ($remaining <= 0.01);
?>
<!doctype html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= esc($t['title']) ?> #<?= esc($sale['invoice_no']) ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <style>
        :root {
            --primary: #2563eb;
            --success: #10b981;
            --danger: #ef4444;
            --bg-main: #f8fafc;
            --surface: #ffffff;
            --border: #e2e8f0;
        }

        body {
            font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Plus Jakarta Sans', sans-serif" ?>;
            background-color: var(--bg-main);
            color: #1e293b;
            padding: 30px 0;
        }

        .bg-pattern {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1;
            background-image: radial-gradient(#cbd5e1 0.8px, transparent 0.8px);
            background-size: 30px 30px; opacity: 0.3;
        }

        .container { max-width: 950px; }

        .invoice-paper {
            background: white; border-radius: 32px; padding: 60px;
            border: 1px solid var(--border); box-shadow: 0 20px 50px -12px rgba(0, 0, 0, 0.05);
            position: relative; overflow: hidden;
        }

        .invoice-paper::before {
            content: ""; position: absolute; top: 0; left: 0; right: 0; height: 10px;
            background: linear-gradient(90deg, var(--primary), #6366f1);
        }

        .invoice-header {
            display: flex; justify-content: space-between; align-items: flex-start;
            margin-bottom: 50px; padding-bottom: 30px; border-bottom: 2px solid #f1f5f9;
        }

        .brand-logo h2 { font-weight: 800; color: var(--primary); letter-spacing: -0.02em; margin: 0; text-transform: uppercase; }
        
        .meta-info h4 { font-weight: 800; margin: 0; font-size: 1.5rem; }
        .meta-info span { font-size: 0.75rem; font-weight: 800; color: #64748b; text-transform: uppercase; letter-spacing: 0.05em; }

        .bill-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 40px; margin-bottom: 40px; }
        .bill-box h6 { font-size: 0.75rem; text-transform: uppercase; font-weight: 800; color: #94a3b8; margin-bottom: 12px; letter-spacing: 0.05em; }
        .bill-box p { font-weight: 700; margin: 0; font-size: 1.1rem; }
        .bill-box .small-meta { color: #64748b; font-weight: 400; font-size: 0.9rem; margin-top: 4px; }

        .status-badge { padding: 6px 16px; border-radius: 50px; font-size: 0.75rem; font-weight: 800; display: inline-block; }
        .st-paid { background: #f0fdf4; color: #166534; }
        .st-partial { background: #fffbeb; color: #92400e; }

        .table thead th { background: #f8fafc; color: #64748b; font-size: 0.75rem; text-transform: uppercase; padding: 18px 20px; font-weight: 800; border: 0; }
        .table tbody td { padding: 20px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }

        .summary-section { margin-top: 40px; display: flex; justify-content: flex-end; }
        .summary-card { width: 320px; background: #f8fafc; border-radius: 24px; padding: 30px; border: 1px solid var(--border); }
        .summary-row { display: flex; justify-content: space-between; padding: 8px 0; font-weight: 600; font-size: 0.95rem; }
        .summary-total { margin-top: 15px; padding-top: 15px; border-top: 2px solid var(--border); font-weight: 800; font-size: 1.4rem; color: var(--primary); }

        .btn-lux { border-radius: 12px; padding: 10px 18px; font-weight: 700; transition: 0.3s; display: inline-flex; align-items: center; gap: 8px; border: 1px solid var(--border); background: #fff; color: #64748b; text-decoration: none; font-size: 0.9rem; }
        .btn-lux:hover { border-color: var(--primary); color: var(--primary); transform: translateY(-2px); }
        .btn-print { background: var(--primary); color: white; border: none; }
        .btn-print:hover { background: #1d4ed8; color: white; box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.2); }
        .btn-pdf { color: #dc3545; }
        .btn-pdf:hover { color: #dc3545; border-color: #dc3545; }

        @media print {
            body { background: white; padding: 0; }
            .bg-pattern, .no-print { display: none !important; }
            .container { max-width: 100%; width: 100%; }
            .invoice-paper { box-shadow: none; border: none; padding: 0; border-radius: 0; }
            .invoice-paper::before { display: none; }
        }
    </style>
</head>
<body>

    <div class="bg-pattern"></div>

    <div class="container">
        <div class="d-flex justify-content-between align-items-center mb-4 no-print">
            <a href="sales_list.php" class="btn-lux"><i class="fa fa-arrow-<?= $is_ar?'right':'left' ?>"></i> <?= esc($t['back']) ?></a>
            <div class="d-flex gap-2">
                <button onclick="generatePDF()" class="btn-lux btn-pdf shadow-sm"><i class="fa fa-file-pdf"></i> <?= esc($t['pdf']) ?></button>
                <button onclick="window.print()" class="btn-lux btn-print shadow-sm"><i class="fa fa-print"></i> <?= esc($t['print']) ?></button>
                <a href="?id=<?= $sale_id ?>&lang=<?= $is_ar?'en':'ar' ?>" class="btn-lux">🌐 <?= $is_ar?'English':'العربية' ?></a>
            </div>
        </div>

        <div class="invoice-paper" id="invoice-card">
            
            <div class="invoice-header">
                <div>
                    <div class="brand-logo"><h2>TOP ACCESSORIES</h2></div>
                    <div class="text-muted small"><?= $is_ar ? 'نظام المبيعات المتطور - 2026' : 'Advanced POS System - 2026' ?></div>
                </div>
                <div class="meta-info text-<?= $is_ar?'start':'end' ?>">
                    <span><?= esc($t['invoice_no']) ?></span>
                    <h4>#<?= esc($sale['invoice_no']) ?></h4>
                    <div class="text-muted fw-bold mt-1"><?= date('M d, Y | H:i', strtotime($sale['created_at'])) ?></div>
                </div>
            </div>

            <div class="bill-grid">
                <div class="bill-box">
                    <h6><?= esc($t['customer']) ?></h6>
                    <p><?= esc($sale['customer_name'] ?: ($is_ar ? 'عميل نقدي' : 'Walk-in Customer')) ?></p>
                    <?php if ($sale['customer_phone']): ?>
                        <div class="small-meta">📞 <?= esc($sale['customer_phone']) ?></div>
                    <?php endif; ?>
                </div>
                <div class="bill-box text-<?= $is_ar?'start':'end' ?>">
                    <h6><?= esc($t['status']) ?></h6>
                    <div class="mb-2">
                        <span class="status-badge <?= $is_paid_full ? 'st-paid' : 'st-partial' ?>">
                            <?= $is_paid_full ? esc($t['paid_status']) : esc($t['partial_status']) ?>
                        </span>
                    </div>
                    <div class="small-meta fw-bold">
                        <?= $sale['payment_method'] === 'cash' ? esc($t['cash']) : esc($t['debt']) ?>
                    </div>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                        <tr>
                            <th style="width: 45%;"><?= esc($t['item']) ?></th>
                            <th class="text-center"><?= esc($t['qty']) ?></th>
                            <th class="text-center"><?= esc($t['price']) ?></th>
                            <th class="text-<?= $is_ar?'start':'end' ?>"><?= esc($t['total']) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($items as $item): ?>
                        <tr>
                            <td>
                                <div class="fw-bold"><?= esc($item['product_name']) ?></div>
                                <div class="text-muted small" style="font-family: monospace;">SKU: <?= esc($item['sku']) ?></div>
                            </td>
                            <td class="text-center fw-bold"><?= number_format($item['qty'], 0) ?></td>
                            <td class="text-center"><?= number_format($item['unit_price'], 2) ?></td>
                            <td class="text-<?= $is_ar?'start':'end' ?> fw-bold">
                                <?= number_format($item['subtotal'], 2) ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="summary-section">
                <div class="summary-card">
                    <h6 class="fw-bold border-bottom pb-2 mb-3"><?= esc($t['summary']) ?></h6>
                    <div class="summary-row">
                        <span class="text-muted">Subtotal</span>
                        <span><?= number_format($sale['total'], 2) ?></span>
                    </div>
                    <div class="summary-row">
                        <span class="text-muted"><?= esc($t['paid']) ?></span>
                        <span class="text-success fw-bold"><?= number_format($sale['paid'], 2) ?></span>
                    </div>
                    <?php if ($remaining > 0): ?>
                    <div class="summary-row">
                        <span class="text-muted"><?= esc($t['due']) ?></span>
                        <span class="text-danger fw-bold"><?= number_format($remaining, 2) ?></span>
                    </div>
                    <?php endif; ?>
                    <div class="summary-row summary-total">
                        <span><?= esc($t['net_total']) ?></span>
                        <span><?= number_format($sale['total'], 2) ?></span>
                    </div>
                </div>
            </div>

            <?php if ($sale['note']): ?>
                <div class="mt-4 p-3 rounded-4 bg-light" style="border-<?= $is_ar?'right':'left' ?>: 4px solid var(--primary);">
                    <small class="fw-bold text-muted d-block mb-1">ملاحظات الفاتورة:</small>
                    <p class="small m-0"><?= esc($sale['note']) ?></p>
                </div>
            <?php endif; ?>

            <div class="mt-5 pt-4 border-top text-center">
                <p class="text-muted small">
                    <?= $is_ar ? 'نشكركم على اختياركم لنا. تم إصدار هذه الفاتورة إلكترونياً.' : 'Thank you for your business. This invoice was electronically generated.' ?>
                </p>
                <div class="fw-bold text-primary">Top Accessories &bull; 2026</div>
            </div>
        </div>
        
        <div class="d-none d-print-block mt-4">
            <div class="d-flex justify-content-between">
                <p class="small">Customer Signature: ________________</p>
                <p class="small">Cashier: <?= esc($_SESSION['username'] ?? 'Admin') ?></p>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>

    <script>
    function generatePDF() {
        // العنصر المستهدف
        const element = document.getElementById('invoice-card');
        
        // إعدادات الملف
        const opt = {
            margin:       10,
            filename:     'Invoice_#<?= $sale['invoice_no'] ?>.pdf',
            image:        { type: 'jpeg', quality: 0.98 },
            html2canvas:  { 
                scale: 2, 
                useCORS: true, 
                letterRendering: true 
            },
            jsPDF:        { unit: 'mm', format: 'a4', orientation: 'portrait' }
        };

        // تنفيذ التحويل والتحميل
        html2pdf().set(opt).from(element).save();
    }
    </script>
</body>
</html>