<?php
session_start();

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

// جلب اسم المستخدم الحالي
$user_name = $_SESSION['user_name'] ?? '';
$user_id = $_SESSION['user_id'];
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 = 'مستخدم غير محدد';
    }
}

// جلب قائمة المخازن
$stores = [];
try {
    $stores = $conn->query("SELECT id, name FROM stores")->fetchAll(PDO::FETCH_ASSOC);
    if (empty($stores)) {
        $stores[] = ['id' => 1, 'name' => 'المخزن الافتراضي'];
    }
} catch (PDOException $e) {
    error_log("Error fetching stores: " . $e->getMessage());
    $stores[] = ['id' => 1, 'name' => 'المخزن الافتراضي'];
}

// البحث بناءً على المخزن المختار
$selected_store_id = isset($_POST['store_id']) ? $_POST['store_id'] : (isset($stores[0]) ? $stores[0]['id'] : 1);
$items = [];
$total_retail_value = 0;
$total_purchase_value = 0;
$total_wholesale_value = 0;

if ($_SERVER["REQUEST_METHOD"] == "POST" || isset($_POST['store_id'])) {
    try {
        // تعديل الاستعلام لجلب سعر الشراء
        $stmt = $conn->prepare("SELECT id, name, barcode, retail_price, wholesale_price, purchase_price, quantity FROM items WHERE store_id = :store_id");
        $stmt->execute([':store_id' => $selected_store_id]);
        $items = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        foreach ($items as $item) {
            $total_retail_value += ($item['retail_price'] ?? 0) * ($item['quantity'] ?? 0);
            // استخدام purchase_price بدلاً من wholesale_price لسعر الشراء
            $total_purchase_value += ($item['purchase_price'] ?? 0) * ($item['quantity'] ?? 0);
            $total_wholesale_value += ($item['wholesale_price'] ?? 0) * ($item['quantity'] ?? 0);
        }
    } catch (PDOException $e) {
        error_log("Error fetching items: " . $e->getMessage());
        $items = [];
    }
}

$potential_retail_profit = $total_retail_value - $total_purchase_value;
$potential_wholesale_profit = $total_wholesale_value - $total_purchase_value;
?>

<!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;
        }

        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #2ECC71;
            padding: 6px 10px;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
            box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.1);
            font-size: 0.9rem;
        }

        .form-control:focus, .form-select:focus {
            border-color: #3498DB;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.5), inset 0 2px 5px rgba(0, 0, 0, 0.1);
            background: #fff;
        }

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

        .btn-search:hover {
            background: linear-gradient(45deg, #2980B9, #2471A3);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.5);
        }

        .summary-container {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            gap: 10px;
        }

        .summary-box {
            flex: 1;
            padding: 15px;
            border-radius: 15px;
            text-align: center;
            font-weight: bold;
            color: #fff;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            transition: transform 0.3s ease;
        }

        .summary-box:hover {
            transform: translateY(-5px);
        }

        .retail-box {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
        }

        .wholesale-box {
            background: linear-gradient(45deg, #F1C40F, #D4AC0D);
        }

        .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);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-warehouse me-2"></i> جرد المخزن</h2>
            <form method="POST" id="searchForm">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-store"></i> اختر المخزن</label>
                        <select class="form-select" name="store_id" required>
                            <?php foreach ($stores as $store): ?>
                                <option value="<?php echo $store['id']; ?>" <?php echo ($selected_store_id == $store['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($store['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"> </label>
                        <button type="submit" class="btn btn-search"><i class="fas fa-search"></i> بحث</button>
                    </div>
                </div>
            </form>

            <!-- كونتينرات الملخصات -->
            <div class="summary-container mt-4">
                <div class="summary-box retail-box">
                    <h4>البيع القطاعي</h4>
                    <p>الإجمالي: <?php echo number_format($total_retail_value, 2); ?> ج.م</p>
                    <p>سعر الشراء: <?php echo number_format($total_purchase_value, 2); ?> ج.م</p>
                    <p>الربح المحتمل: <?php echo number_format($potential_retail_profit, 2); ?> ج.م</p>
                </div>
                <div class="summary-box wholesale-box">
                    <h4>البيع الجملي</h4>
                    <p>الإجمالي: <?php echo number_format($total_wholesale_value, 2); ?> ج.م</p>
                    <p>سعر الشراء: <?php echo number_format($total_purchase_value, 2); ?> ج.م</p>
                    <p>الربح المحتمل: <?php echo number_format($potential_wholesale_profit, 2); ?> ج.م</p>
                </div>
            </div>

            <!-- جدول الأصناف -->
            <div class="table-responsive mt-4">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>اسم الصنف</th>
                            <th>الباركود</th>
                            <th>الكمية</th>
                            <th>سعر البيع القطاعي</th>
                            <th>سعر البيع الجملي</th>
                            <th>سعر الشراء</th>
                            <th>القيمة القطاعية</th>
                            <th>القيمة الجملية</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($items)): ?>
                            <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($item['name'] ?? ''); ?></td>
                                    <td><?php echo htmlspecialchars($item['barcode'] ?? ''); ?></td>
                                    <td><?php echo $item['quantity'] ?? 0; ?></td>
                                    <td><?php echo number_format($item['retail_price'] ?? 0, 2); ?> ج.م</td>
                                    <td><?php echo number_format($item['wholesale_price'] ?? 0, 2); ?> ج.م</td>
                                    <td><?php echo number_format($item['purchase_price'] ?? 0, 2); ?> ج.م</td>
                                    <td><?php echo number_format(($item['retail_price'] ?? 0) * ($item['quantity'] ?? 0), 2); ?> ج.م</td>
                                    <td><?php echo number_format(($item['wholesale_price'] ?? 0) * ($item['quantity'] ?? 0), 2); ?> ج.م</td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="8" style="text-align: center; color: #E74C3C;">لا توجد أصناف في هذا المخزن.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

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