<?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 = 'مستخدم غير محدد';
    }
}

// جلب المخازن
$stores = [];
try {
    $stores = $conn->query("SELECT id, name FROM stores ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching stores: " . $e->getMessage());
    $stores = [];
}

// جلب الأصناف
$items = [];
try {
    $items = $conn->query("SELECT id, name, quantity FROM items ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching items: " . $e->getMessage());
    $items = [];
}

// توليد رقم التحويل التلقائي (مثال: ST-YYYYMMDD-XXX)
$transfer_number = '';
try {
    $stmt = $conn->query("SELECT MAX(id) FROM store_transfers");
    $last_id = $stmt->fetchColumn() ?: 0;
    $transfer_number = "ST-" . date('Ymd') . "-" . sprintf("%03d", $last_id + 1);
} catch (PDOException $e) {
    error_log("Error generating transfer number: " . $e->getMessage());
    $transfer_number = "ST-" . date('Ymd') . "-001";
}

// معالجة عملية التحويل
$success_message = '';
$error_message = '';

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['transfer'])) {
    $from_store_id = $_POST['from_store_id'] ?? 0;
    $to_store_id = $_POST['to_store_id'] ?? 0;
    $item_id = $_POST['item_id'] ?? 0;
    $quantity = floatval($_POST['quantity'] ?? 0);
    $date = $_POST['date'] ?? date('Y-m-d H:i:s');

    if ($from_store_id <= 0 || $to_store_id <= 0 || $item_id <= 0 || $quantity <= 0) {
        $error_message = "جميع الحقول مطلوبة ويجب أن تكون الكمية موجبة!";
    } elseif ($from_store_id == $to_store_id) {
        $error_message = "لا يمكن التحويل إلى نفس المخزن!";
    } else {
        try {
            $conn->beginTransaction();

            // التحقق من الكمية المتاحة في جدول items
            $stmt = $conn->prepare("SELECT quantity FROM items WHERE id = :item_id");
            $stmt->execute([':item_id' => $item_id]);
            $available_quantity = $stmt->fetchColumn() ?: 0;

            if ($available_quantity < $quantity) {
                throw new Exception("الكمية المطلوبة غير متاحة!");
            }

            // تحديث الكمية في جدول items (تقليل الكمية)
            $stmt = $conn->prepare("UPDATE items SET quantity = quantity - :quantity WHERE id = :item_id");
            $stmt->execute([':quantity' => $quantity, ':item_id' => $item_id]);

            // تسجيل عملية التحويل
            $stmt = $conn->prepare("INSERT INTO store_transfers (transfer_number, from_store_id, to_store_id, item_id, quantity, date, user_id) 
                                    VALUES (:transfer_number, :from_store_id, :to_store_id, :item_id, :quantity, :date, :user_id)");
            $stmt->execute([
                ':transfer_number' => $transfer_number,
                ':from_store_id' => $from_store_id,
                ':to_store_id' => $to_store_id,
                ':item_id' => $item_id,
                ':quantity' => $quantity,
                ':date' => $date,
                ':user_id' => $user_id
            ]);

            $conn->commit();
            $success_message = "تم تنفيذ التحويل بنجاح! رقم التحويل: $transfer_number";
        } catch (Exception $e) {
            $conn->rollBack();
            error_log("Error during store transfer: " . $e->getMessage());
            $error_message = "فشل التحويل: " . $e->getMessage();
        }
    }
}

// جلب سجل التحويلات بناءً على البحث بين تاريخين
$transfers = [];
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] . ' 00:00:00' : date('Y-m-d 00:00:00', strtotime('-30 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] . ' 23:59:59' : date('Y-m-d 23:59:59');

try {
    $stmt = $conn->prepare("SELECT st.*, s1.name AS from_store_name, s2.name AS to_store_name, i.name AS item_name, u.username 
                           FROM store_transfers st 
                           LEFT JOIN stores s1 ON st.from_store_id = s1.id 
                           LEFT JOIN stores s2 ON st.to_store_id = s2.id 
                           LEFT JOIN items i ON st.item_id = i.id 
                           LEFT JOIN users u ON st.user_id = u.id 
                           WHERE st.date BETWEEN :start_date AND :end_date 
                           ORDER BY st.date DESC");
    $stmt->execute([':start_date' => $start_date, ':end_date' => $end_date]);
    $transfers = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching transfers: " . $e->getMessage());
    $transfers = [];
}
?>

<!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 {
            border-radius: 10px;
            padding: 6px 15px;
            font-weight: bold;
            transition: all 0.4s ease;
            position: relative;
            overflow: hidden;
            font-size: 0.9rem;
        }

        .btn-transfer {
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
        }

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

        .btn-cancel {
            background: linear-gradient(45deg, #E74C3C, #C0392B);
            border: none;
            color: #fff;
        }

        .btn-cancel:hover {
            background: linear-gradient(45deg, #C0392B, #A93226);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.5);
        }

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

        .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%;
            margin-top: 20px;
        }

        .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-exchange-alt me-2"></i> تحويل بين المخازن</h2>
            <?php if ($success_message): ?>
                <div class="success-message"><?php echo $success_message; ?></div>
            <?php endif; ?>
            <?php if ($error_message): ?>
                <div class="error-message"><?php echo $error_message; ?></div>
            <?php endif; ?>

            <!-- نموذج التحويل -->
            <form method="POST" id="transferForm">
                <div class="row g-3">
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-hashtag"></i> رقم التحويل</label>
                        <input type="text" class="form-control" value="<?php echo $transfer_number; ?>" readonly>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-calendar-alt"></i> التاريخ</label>
                        <input type="datetime-local" class="form-control" name="date" value="<?php echo date('Y-m-d\TH:i'); ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-warehouse"></i> من مخزن</label>
                        <select class="form-select" name="from_store_id" id="fromStore" required>
                            <option value="">اختر المخزن</option>
                            <?php foreach ($stores as $store): ?>
                                <option value="<?php echo $store['id']; ?>"><?php echo htmlspecialchars($store['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-warehouse"></i> إلى مخزن</label>
                        <select class="form-select" name="to_store_id" required>
                            <option value="">اختر المخزن</option>
                            <?php foreach ($stores as $store): ?>
                                <option value="<?php echo $store['id']; ?>"><?php echo htmlspecialchars($store['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-box"></i> الصنف</label>
                        <select class="form-select" name="item_id" id="item" required>
                            <option value="">اختر الصنف</option>
                            <?php foreach ($items as $item): ?>
                                <option value="<?php echo $item['id']; ?>" data-quantity="<?php echo $item['quantity']; ?>"><?php echo htmlspecialchars($item['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-cubes"></i> الكمية المتاحة</label>
                        <input type="text" class="form-control" id="availableQuantity" value="0" readonly>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-cube"></i> الكمية المطلوبة</label>
                        <input type="number" step="0.01" class="form-control" name="quantity" placeholder="أدخل الكمية" required>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-transfer" name="transfer"><i class="fas fa-exchange-alt"></i> تنفيذ التحويل</button>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-cancel" onclick="window.location.href='dashboard.php'"><i class="fas fa-times"></i> إلغاء</button>
                    </div>
                </div>
            </form>

            <!-- نموذج البحث -->
            <form method="GET" class="mb-4 mt-4">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-calendar"></i> من تاريخ</label>
                        <input type="date" class="form-control" name="start_date" value="<?php echo isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-30 days')); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-calendar"></i> إلى تاريخ</label>
                        <input type="date" class="form-control" name="end_date" value="<?php echo isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d'); ?>">
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-transfer"><i class="fas fa-search"></i> بحث</button>
                    </div>
                </div>
            </form>

            <!-- جدول سجل التحويلات -->
            <div class="table-responsive" style="max-height: 40vh; overflow-y: auto;">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>رقم التحويل</th>
                            <th>من مخزن</th>
                            <th>إلى مخزن</th>
                            <th>الصنف</th>
                            <th>الكمية</th>
                            <th>التاريخ</th>
                            <th>المستخدم</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($transfers)): ?>
                            <?php foreach ($transfers as $index => $transfer): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($transfer['transfer_number']); ?></td>
                                    <td><?php echo htmlspecialchars($transfer['from_store_name']); ?></td>
                                    <td><?php echo htmlspecialchars($transfer['to_store_name']); ?></td>
                                    <td><?php echo htmlspecialchars($transfer['item_name']); ?></td>
                                    <td><?php echo number_format($transfer['quantity'], 2); ?></td>
                                    <td><?php echo date('Y-m-d H:i', strtotime($transfer['date'])); ?></td>
                                    <td><?php echo htmlspecialchars($transfer['username'] ?? 'غير محدد'); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="7" 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>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const form = document.getElementById('transferForm');
            const itemSelect = document.getElementById('item');
            const availableQuantityInput = document.getElementById('availableQuantity');
            const quantityInput = document.querySelector('input[name="quantity"]');

            // تحديث الكمية المتاحة عند اختيار الصنف
            function updateAvailableQuantity() {
                const itemId = itemSelect.value;
                if (itemId) {
                    const selectedOption = itemSelect.options[itemSelect.selectedIndex];
                    const availableQuantity = parseFloat(selectedOption.getAttribute('data-quantity')) || 0;
                    availableQuantityInput.value = availableQuantity;
                } else {
                    availableQuantityInput.value = 0;
                }
            }

            itemSelect.addEventListener('change', updateAvailableQuantity);

            // التحقق من الكمية المطلوبة قبل الإرسال
            form.addEventListener('submit', function(e) {
                const availableQuantity = parseFloat(availableQuantityInput.value) || 0;
                const requestedQuantity = parseFloat(quantityInput.value) || 0;

                if (requestedQuantity > availableQuantity) {
                    e.preventDefault();
                    alert('الكمية المطلوبة أكبر من الكمية المتاحة!');
                }
            });
        });
    </script>
</body>
</html>