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

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';

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

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

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

// جلب بيانات الفاتورة مع المورد
$stmt = $pdo->prepare("SELECT p.*, s.name as supplier_name, s.phone as supplier_phone 
                        FROM purchases p 
                        LEFT JOIN suppliers s ON p.supplier_id = s.id 
                        WHERE p.id = ?");
$stmt->execute([$id]);
$invoice = $stmt->fetch(PDO::FETCH_ASSOC);

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

// جلب أصناف الفاتورة
$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 pi.*, pr.sku, pr.$nameField as product_name 
                              FROM purchase_items pi 
                              JOIN products pr ON pi.product_id = pr.id 
                              WHERE pi.purchase_id = ?");
$stmt_items->execute([$id]);
$items = $stmt_items->fetchAll(PDO::FETCH_ASSOC);

$remaining = $invoice['total'] - $invoice['paid'];
?>
<!doctype html>
<html lang="<?= $is_ar ? 'ar' : 'en' ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= $is_ar ? 'فاتورة شراء' : 'Purchase Invoice' ?> #<?= $id ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #2563eb;
            --bg: #f8fafc;
            --border: #e2e8f0;
            --text-main: #1e293b;
        }

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

        .container { max-width: 900px; }

        .invoice-card {
            background: white; border-radius: 24px; padding: 50px;
            border: 1px solid var(--border); box-shadow: 0 10px 40px -10px rgba(0,0,0,0.05);
            position: relative;
        }

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

        .brand-name { font-size: 1.8rem; font-weight: 800; color: var(--primary); letter-spacing: -0.02em; }
        .invoice-label { font-size: 2.5rem; font-weight: 800; opacity: 0.1; position: absolute; top: 30px; <?= $is_ar ? 'left' : 'right' ?>: 50px; text-transform: uppercase; }

        .meta-section { display: grid; grid-template-columns: 1fr 1fr; gap: 40px; margin-bottom: 40px; }
        .meta-box h6 { font-size: 0.75rem; text-transform: uppercase; color: #64748b; font-weight: 700; margin-bottom: 10px; letter-spacing: 0.05em; }
        .meta-box p { font-weight: 600; margin: 0; }

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

        .summary-wrapper {
            margin-top: 40px; display: flex; justify-content: flex-end;
        }
        .summary-table { width: 300px; }
        .summary-row { display: flex; justify-content: space-between; padding: 10px 0; }
        .summary-total { border-top: 2px solid var(--primary); margin-top: 10px; padding-top: 15px; font-weight: 800; font-size: 1.2rem; color: var(--primary); }

        .btn-print {
            background: var(--primary); color: white; border: none; border-radius: 12px;
            padding: 12px 25px; font-weight: 700; transition: 0.2s; text-decoration: none;
        }
        .btn-print:hover { background: #1d4ed8; color: white; transform: translateY(-2px); }

        @media print {
            body { background: white; padding: 0; }
            .invoice-card { border: none; box-shadow: none; padding: 0; }
            .no-print { display: none !important; }
        }
    </style>
</head>
<body>

    <div class="container">
        <!-- Back and Print Buttons -->
        <div class="d-flex justify-content-between align-items-center mb-4 no-print">
            <a href="purchase_view.php" class="btn btn-light rounded-pill px-4 fw-bold border">
                <?= $is_ar ? '← العودة للسجل' : '← Back to Log' ?>
            </a>
            <button onclick="window.print()" class="btn-print">
                <?= $is_ar ? 'طباعة الفاتورة 🖨️' : 'Print Invoice 🖨️' ?>
            </button>
        </div>

        <div class="invoice-card">
            <div class="invoice-label"><?= $is_ar ? 'فاتورة' : 'INVOICE' ?></div>
            
            <div class="invoice-header">
                <div>
                    <div class="brand-name">TOP ACCESSORIES</div>
                    <div class="text-muted small"><?= $is_ar ? 'نظام الإدارة المتكامل' : 'Integrated Management System' ?></div>
                </div>
                <div class="text-<?= $is_ar ? 'start' : 'end' ?>">
                    <h4 class="fw-bold m-0">#<?= $id ?></h4>
                    <div class="text-muted"><?= date('M d, Y', strtotime($invoice['created_at'])) ?></div>
                </div>
            </div>

            <div class="meta-section">
                <div class="meta-box">
                    <h6><?= $is_ar ? 'مورد الفاتورة' : 'Supplier Details' ?></h6>
                    <p class="fs-5"><?= esc($invoice['supplier_name'] ?: ($is_ar ? 'نقدي / عميل عام' : 'Cash / Walk-in')) ?></p>
                    <div class="text-muted"><?= esc($invoice['supplier_phone']) ?></div>
                </div>
                <div class="meta-box text-<?= $is_ar ? 'start' : 'end' ?>">
                    <h6><?= $is_ar ? 'معلومات الفاتورة' : 'Invoice Meta' ?></h6>
                    <p><?= $is_ar ? 'الحالة:' : 'Status:' ?> <?= $remaining <= 0 ? ($is_ar ? 'مدفوعة بالكامل' : 'Fully Paid') : ($is_ar ? 'آجل / متبقي' : 'Partial') ?></p>
                    <div class="text-muted small"><?= esc($invoice['note']) ?></div>
                </div>
            </div>

            <table class="table table-pro">
                <thead>
                    <tr>
                        <th><?= $is_ar ? 'الصنف' : 'Item' ?></th>
                        <th class="text-center">SKU</th>
                        <th class="text-center"><?= $is_ar ? 'الكمية' : 'Qty' ?></th>
                        <th class="text-center"><?= $is_ar ? 'السعر' : 'Unit Cost' ?></th>
                        <th class="text-<?= $is_ar ? 'start' : 'end' ?>"><?= $is_ar ? 'الإجمالي' : 'Total' ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($items as $item): ?>
                    <tr>
                        <td>
                            <div class="fw-bold"><?= esc($item['product_name']) ?></div>
                        </td>
                        <td class="text-center text-muted small"><?= esc($item['sku']) ?></td>
                        <td class="text-center"><?= number_format($item['qty'], 2) ?></td>
                        <td class="text-center"><?= number_format($item['cost'], 2) ?></td>
                        <td class="text-<?= $is_ar ? 'start' : 'end' ?> fw-bold"><?= number_format($item['subtotal'], 2) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <div class="summary-wrapper">
                <div class="summary-table">
                    <div class="summary-row">
                        <span class="text-muted"><?= $is_ar ? 'الإجمالي الفرعي' : 'Subtotal' ?></span>
                        <span class="fw-bold"><?= number_format($invoice['total'], 2) ?></span>
                    </div>
                    <div class="summary-row">
                        <span class="text-muted"><?= $is_ar ? 'المدفوع نقداً' : 'Total Paid' ?></span>
                        <span class="text-success fw-bold"><?= number_format($invoice['paid'], 2) ?></span>
                    </div>
                    <?php if($remaining > 0): ?>
                    <div class="summary-row">
                        <span class="text-muted"><?= $is_ar ? 'المتبقي (دين)' : 'Remaining Debt' ?></span>
                        <span class="text-danger fw-bold"><?= number_format($remaining, 2) ?></span>
                    </div>
                    <?php endif; ?>
                    <div class="summary-row summary-total">
                        <span><?= $is_ar ? 'صافي الفاتورة' : 'Total Net' ?></span>
                        <span><?= number_format($invoice['total'], 2) ?></span>
                    </div>
                </div>
            </div>

            <div class="mt-5 pt-4 border-top text-center text-muted small">
                <p><?= $is_ar ? 'شكراً لتعاملكم مع Top Accessories. تم إصدار هذه الفاتورة إلكترونياً.' : 'Thank you for choosing Top Accessories. This is an electronically generated invoice.' ?></p>
            </div>
        </div>
    </div>

</body>
</html>