<?php
session_start();

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

require_once 'db_connect.php';

// جلب بيانات المستخدم الحالي
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? '';
if (empty($user_name)) {
    try {
        $stmt = $conn->prepare("SELECT username FROM users WHERE id = :user_id");
        $stmt->execute([':user_id' => $user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        if (!empty($user) && isset($user['username'])) {
            $user_name = $user['username'];
            $_SESSION['user_name'] = $user_name;
        }
    } catch (PDOException $e) {
        error_log("Error fetching user name: " . $e->getMessage());
        $user_name = 'مستخدم غير محدد';
    }
}

// جلب بيانات الفاتورة بناءً على المعرف
$invoice = [];
$items = [];
$error_message = '';

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $invoice_id = intval($_GET['id']);

    try {
        // جلب بيانات الفاتورة
        $stmt = $conn->prepare("
            SELECT pi.id, pi.invoice_number, pi.date, pi.total, pi.payment_type, pi.remaining_amount, 
                   s.name AS supplier_name, t.name AS treasury_name 
            FROM purchase_invoices pi 
            LEFT JOIN suppliers s ON pi.supplier_id = s.id 
            LEFT JOIN treasuries t ON pi.treasury_id = t.id 
            WHERE pi.id = :id
        ");
        $stmt->execute([':id' => $invoice_id]);
        $invoice = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

        // جلب الأصناف المرتبطة بالفاتورة
        $stmt = $conn->prepare("
            SELECT pii.quantity, pii.price, i.name, i.barcode 
            FROM purchase_invoice_items pii 
            LEFT JOIN items i ON pii.item_id = i.id 
            WHERE pii.invoice_id = :id
        ");
        $stmt->execute([':id' => $invoice_id]);
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        if (empty($invoice)) {
            $error_message = "لا يوجد فاتورة بهذا المعرف!";
        }
    } catch (PDOException $e) {
        error_log("Error fetching invoice details: " . $e->getMessage());
        $error_message = "حدث خطأ أثناء جلب بيانات الفاتورة!";
    }
} else {
    $error_message = "معرف الفاتورة غير صالح!";
    header("Location: purchase_invoices.php?error=invalid_id");
    exit();
}
?>

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Astra - عرض فاتورة شراء</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            direction: rtl;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #2ECC71, #3498DB, #E74C3C);
            overflow-x: hidden;
            animation: gradientShift 10s ease infinite;
            background-size: 400% 400%;
        }

        @keyframes gradientShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .container-fluid {
            padding: 20px;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            padding: 20px;
            margin-bottom: 20px;
            animation: fadeIn 1s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        h2 {
            color: #2ECC71;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 0 0 5px rgba(46, 204, 113, 0.5);
        }

        .form-label {
            color: #3498DB;
            font-weight: bold;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            font-size: 0.9rem;
        }

        .form-label i {
            margin-left: 8px;
            color: #2ECC71;
        }

        .error-message {
            color: #E74C3C;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            animation: fadeIn 0.5s ease-in-out;
        }

        .table {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            width: 100%;
        }

        .table thead {
            background: #2ECC71;
            color: #fff;
        }

        .table tbody tr:hover {
            background: rgba(46, 204, 113, 0.1);
        }

        .btn-back {
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
            border-radius: 10px;
            padding: 6px 15px;
            font-weight: bold;
            transition: all 0.4s ease;
            position: relative;
            overflow: hidden;
            font-size: 0.9rem;
        }

        .btn-back:hover {
            background: linear-gradient(45deg, #2980B9, #2471A3);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.5);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-eye me-2"></i> عرض فاتورة شراء</h2>
            <?php if ($error_message): ?>
                <div class="error-message"><?php echo $error_message; ?></div>
            <?php else: ?>
                <?php if (!empty($invoice)): ?>
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label"><i class="fas fa-hashtag"></i> رقم الفاتورة</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($invoice['invoice_number']); ?>" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><i class="fas fa-calendar"></i> التاريخ</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($invoice['date']); ?>" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><i class="fas fa-user"></i> المورد</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($invoice['supplier_name'] ?? 'غير محدد'); ?>" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><i class="fas fa-vault"></i> الخزنة</label>
                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($invoice['treasury_name'] ?? 'غير محدد'); ?>" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><i class="fas fa-money-bill"></i> نوع الدفع</label>
                            <input type="text" class="form-control" value="<?php echo $invoice['payment_type'] === 'cash' ? 'نقدي' : 'آجل'; ?>" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><i class="fas fa-money-bill-wave"></i> الإجمالي</label>
                            <input type="text" class="form-control" value="<?php echo number_format($invoice['total'], 2); ?> ج.م" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label"><i class="fas fa-money-check"></i> المتبقي</label>
                            <input type="text" class="form-control" value="<?php echo number_format($invoice['remaining_amount'], 2); ?> ج.م" readonly>
                        </div>
                    </div>

                    <!-- جدول الأصناف -->
                    <div class="table-responsive" style="max-height: 40vh; overflow-y: auto; margin-top: 20px;">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>اسم الصنف</th>
                                    <th>الباركود</th>
                                    <th>الكمية</th>
                                    <th>السعر</th>
                                    <th>الإجمالي</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($items)): ?>
                                    <tr>
                                        <td colspan="5" style="text-align: center; color: #E74C3C;">لا توجد أصناف في هذه الفاتورة.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($items as $item): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['name'] ?? 'غير محدد'); ?></td>
                                            <td><?php echo htmlspecialchars($item['barcode'] ?? 'غير محدد'); ?></td>
                                            <td><?php echo htmlspecialchars($item['quantity']); ?></td>
                                            <td><?php echo number_format($item['price'], 2); ?> ج.م</td>
                                            <td><?php echo number_format($item['quantity'] * $item['price'], 2); ?> ج.م</td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            <?php endif; ?>

            <!-- زر العودة -->
            <div style="text-align: center; margin-top: 20px;">
                <a href="purchase_invoices.php" class="btn btn-back"><i class="fas fa-arrow-left me-2"></i> العودة إلى قائمة الفواتير</a>
            </div>
        </div>
    </div>
</body>
</html>