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

if (session_status() === PHP_SESSION_NONE) session_start();

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

$is_ar = ($_SESSION['lang'] ?? 'ar') === 'ar';
$supplier_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

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

// 1. جلب بيانات المورد
$stmt = $pdo->prepare("SELECT * FROM suppliers WHERE id = ?");
$stmt->execute([$supplier_id]);
$supplier = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$supplier) {
    die($is_ar ? "المورد غير موجود." : "Supplier not found.");
}

/**
 * 2. جلب الحركات (دمج الفواتير والسندات)
 * ملاحظة: تم تغيير total_amount إلى total لحل خطأ SQL
 * يرجى التأكد من اسم العمود في جدول purchases لديك
 */
$query = "
    (SELECT id, amount, type, description, created_at FROM supplier_transactions WHERE supplier_id = ?)
    UNION ALL
    (SELECT id, total as amount, 'purchase' as type, CONCAT('Invoice #', id) as description, created_at FROM purchases WHERE supplier_id = ?)
    ORDER BY created_at DESC
";

$stmt_tx = $pdo->prepare($query);
$stmt_tx->execute([$supplier_id, $supplier_id]);
$transactions = $stmt_tx->fetchAll(PDO::FETCH_ASSOC);

// 3. حساب إحصائيات سريعة
$total_paid = 0;
$total_purchases = 0;
foreach($transactions as $tx) {
    if($tx['type'] === 'out') $total_paid += $tx['amount'];
    elseif($tx['type'] === 'purchase') $total_purchases += $tx['amount'];
}
?>
<!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><?= esc($supplier['name']) ?> | <?= $is_ar ? 'كشف حساب شامل' : 'Full Statement' ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&family=Plus+Jakarta+Sans:wght@400;500;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;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
        }

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

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

        .container { max-width: 1100px; }

        .btn-back {
            background: white; border: 1px solid var(--border); padding: 8px 20px;
            border-radius: 12px; color: #64748b; text-decoration: none; font-weight: 600;
            transition: all 0.2s; display: inline-flex; align-items: center; gap: 8px;
        }
        .btn-back:hover { background: #f1f5f9; color: var(--primary); }

        .profile-card {
            background: white; border-radius: 24px; padding: 32px;
            border: 1px solid var(--border); box-shadow: 0 10px 30px -10px rgba(0,0,0,0.05);
            margin-bottom: 30px; display: flex; justify-content: space-between; align-items: center;
            flex-wrap: wrap; gap: 20px;
        }

        .balance-box {
            background: #f8fafc; border: 1px solid var(--border); padding: 15px 25px;
            border-radius: 18px; text-align: center; min-width: 140px;
        }
        .balance-value { font-size: 1.4rem; font-weight: 800; display: block; }
        .balance-label { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.1em; color: #64748b; margin-bottom: 4px; display: block; }

        .status-pill { padding: 4px 12px; border-radius: 50px; font-size: 0.75rem; font-weight: 700; }
        .status-debt { background: #fef2f2; color: #dc2626; }
        .status-credit { background: #f0fdf4; color: #16a34a; }

        .tx-card {
            background: white; border-radius: 24px; border: 1px solid var(--border);
            box-shadow: 0 10px 30px -10px rgba(0,0,0,0.05); overflow: hidden;
        }

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

        .tx-icon {
            width: 36px; height: 36px; border-radius: 10px; display: inline-flex;
            align-items: center; justify-content: center; font-size: 1rem;
        }
        .type-purchase { background: #fff7ed; color: #f97316; } /* فاتورة */
        .type-out { background: #f0fdf4; color: #10b981; }      /* دفعة */
        .type-in { background: #fef2f2; color: #ef4444; }       /* استرداد */

        @media (max-width: 768px) {
            .profile-card { flex-direction: column; text-align: center; }
            .d-flex.gap-3 { flex-direction: column; width: 100%; }
        }
    </style>
</head>
<body>

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

    <div class="container">
        <!-- Header Nav -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <a href="suppliers.php" class="btn-back">
                <?= $is_ar ? '← العودة للموردين' : '← Back to Suppliers' ?>
            </a>
            <div class="text-muted small"><?= $is_ar ? 'تاريخ الاستخراج:' : 'Generated on:' ?> <?= date('Y-m-d') ?></div>
        </div>

        <!-- Supplier Profile Card -->
        <div class="profile-card">
            <div class="supplier-meta">
                <div class="d-flex align-items-center gap-3">
                    <div style="width: 60px; height: 60px; background: var(--primary); color: white; border-radius: 18px; display: flex; align-items: center; justify-content: center; font-size: 1.8rem; font-weight: 700;">
                        <?= strtoupper(substr($supplier['name'] ?? 'S', 0, 1)) ?>
                    </div>
                    <div>
                        <h1 class="mb-1"><?= esc($supplier['name']) ?></h1>
                        <p class="mb-0">📞 <?= esc($supplier['phone'] ?: ($is_ar ? 'لا يوجد هاتف' : 'No phone')) ?></p>
                    </div>
                </div>
            </div>

            <div class="d-flex gap-3">
                <div class="balance-box">
                    <span class="balance-label"><?= $is_ar ? 'إجمالي المشتريات' : 'Total Purchases' ?></span>
                    <span class="balance-value text-dark"><?= number_format($total_purchases, 2) ?></span>
                </div>
                <div class="balance-box">
                    <span class="balance-label"><?= $is_ar ? 'إجمالي المدفوع' : 'Total Paid' ?></span>
                    <span class="balance-value text-success"><?= number_format($total_paid, 2) ?></span>
                </div>
                <div class="balance-box">
                    <span class="balance-label"><?= $is_ar ? 'الرصيد المتبقي' : 'Balance Due' ?></span>
                    <?php 
                        $b = floatval($supplier['balance']);
                        $b_class = $b > 0 ? 'text-danger' : ($b < 0 ? 'text-success' : '');
                    ?>
                    <span class="balance-value <?= $b_class ?>"><?= number_format(abs($b), 2) ?></span>
                    <span class="status-pill <?= $b > 0 ? 'status-debt' : ($b < 0 ? 'status-credit' : '') ?>">
                        <?= $b > 0 ? ($is_ar ? 'مطلوب للمورد' : 'Payable') : ($b < 0 ? ($is_ar ? 'فائض لك' : 'Credit') : ($is_ar ? 'خالص' : 'Settled')) ?>
                    </span>
                </div>
            </div>
        </div>

        <!-- Combined Ledger Table -->
        <div class="tx-card">
            <div class="p-4 border-bottom d-flex justify-content-between align-items-center bg-light">
                <h6 class="m-0 fw-bold"><?= $is_ar ? 'كشف الحركات التفصيلي (فواتير + دفعات)' : 'Detailed Statement (Invoices + Payments)' ?></h6>
                <button onclick="window.print()" class="btn btn-sm btn-outline-secondary px-3">
                    <?= $is_ar ? 'طباعة الكشف' : 'Print Statement' ?>
                </button>
            </div>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th><?= $is_ar ? 'التاريخ' : 'Date' ?></th>
                            <th><?= $is_ar ? 'النوع' : 'Type' ?></th>
                            <th><?= $is_ar ? 'البيان / الملاحظات' : 'Description' ?></th>
                            <th class="text-end"><?= $is_ar ? 'المبلغ' : 'Amount' ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($transactions as $tx): ?>
                        <tr>
                            <td class="text-muted small"><?= date('Y-m-d H:i', strtotime($tx['created_at'])) ?></td>
                            <td>
                                <div class="d-flex align-items-center gap-2">
                                    <?php if($tx['type'] === 'purchase'): ?>
                                        <span class="tx-icon type-purchase">📄</span>
                                        <span class="fw-bold small text-orange-600"><?= $is_ar ? 'فاتورة شراء' : 'Purchase' ?></span>
                                    <?php elseif($tx['type'] === 'out'): ?>
                                        <span class="tx-icon type-out">💸</span>
                                        <span class="fw-bold small text-success"><?= $is_ar ? 'دفعة نقدية' : 'Payment' ?></span>
                                    <?php else: ?>
                                        <span class="tx-icon type-in">↩</span>
                                        <span class="fw-bold small text-danger"><?= $is_ar ? 'استرداد' : 'Refund' ?></span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td><span class="text-secondary small"><?= esc($tx['description'] ?: '---') ?></span></td>
                            <td class="text-end fw-bold">
                                <?= number_format($tx['amount'], 2) ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        
                        <?php if(empty($transactions)): ?>
                        <tr>
                            <td colspan="4" class="text-center py-5 text-muted italic">
                                <?= $is_ar ? 'لا توجد فواتير أو حركات مسجلة.' : 'No invoices or transactions found.' ?>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="text-center mt-5 text-muted small">
            &copy; 2025 Top Accessories Tools &bull; Financial Ledger System
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>