<?php
session_start();
include("layout.php");
include("db.php");

// Handle transfer actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $transfer_id = $_POST['transfer_id'];
    $user_id = $_SESSION['user_id'] ?? 1; // Get from session
    
    switch ($_POST['action']) {
        case 'approve_transfer':
            // Get transfer details
            $transfer_query = "SELECT * FROM stock_transfers WHERE id = ?";
            $stmt = $conn->prepare($transfer_query);
            $stmt->bind_param("i", $transfer_id);
            $stmt->execute();
            $transfer = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            // Get transfer items
            $items_query = "SELECT * FROM stock_transfer_items WHERE transfer_id = ?";
            $stmt = $conn->prepare($items_query);
            $stmt->bind_param("i", $transfer_id);
            $stmt->execute();
            $items_result = $stmt->get_result();
            $stmt->close();
            
            // Process each item - Create inventory movements immediately upon approval
            while ($item = $items_result->fetch_assoc()) {
                // Deduct from source store
                $conn->query("
                    INSERT INTO inventory_movements (item_id, store_id, movement_type, quantity, reference_type, reference_id, created_at)
                    VALUES ({$item['item_id']}, {$transfer['from_store_id']}, 'out', {$item['quantity']}, 'stock_transfer_out', $transfer_id, NOW())
                ");
                
                // Add to destination store
                $conn->query("
                    INSERT INTO inventory_movements (item_id, store_id, movement_type, quantity, reference_type, reference_id, created_at)
                    VALUES ({$item['item_id']}, {$transfer['to_store_id']}, 'in', {$item['quantity']}, 'stock_transfer_in', $transfer_id, NOW())
                ");
            }
            
            // Update transfer status
            $stmt = $conn->prepare("UPDATE stock_transfers SET status = 'approved', approved_by = ? WHERE id = ?");
            $stmt->bind_param("ii", $user_id, $transfer_id);
            $stmt->execute();
            $stmt->close();
            
            header("Location: stock_transfer_approval.php?success=1");
            exit;
            break;
            
        case 'reject_transfer':
            $stmt = $conn->prepare("UPDATE stock_transfers SET status = 'cancelled' WHERE id = ?");
            $stmt->bind_param("i", $transfer_id);
            $stmt->execute();
            $stmt->close();
            
            header("Location: stock_transfer_approval.php?success=2");
            exit;
            break;
            
        case 'mark_in_transit':
            $stmt = $conn->prepare("UPDATE stock_transfers SET status = 'in_transit' WHERE id = ?");
            $stmt->bind_param("i", $transfer_id);
            $stmt->execute();
            $stmt->close();
            
            header("Location: stock_transfer_approval.php?success=3");
            exit;
            break;
            
        case 'receive_transfer':
            // Update transfer status to received (inventory movements already created during approval)
            $stmt = $conn->prepare("UPDATE stock_transfers SET status = 'received', received_by = ? WHERE id = ?");
            $stmt->bind_param("ii", $user_id, $transfer_id);
            $stmt->execute();
            $stmt->close();
            
            header("Location: stock_transfer_approval.php?success=4");
            exit;
            break;
    }
}

// Get transfers list with filters
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$store_filter = isset($_GET['store_id']) ? $_GET['store_id'] : '';

$where_conditions = [];
$params = [];
$param_types = '';

if ($status_filter) {
    $where_conditions[] = "st.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if ($store_filter) {
    $where_conditions[] = "(st.from_store_id = ? OR st.to_store_id = ?)";
    $params[] = $store_filter;
    $params[] = $store_filter;
    $param_types .= 'ii';
}

$where_clause = $where_conditions ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

$transfers_query = "
    SELECT st.*, 
           fs.store_name as from_store_name, fs.store_code as from_store_code,
           ts.store_name as to_store_name, ts.store_code as to_store_code,
           u1.username as requested_by_name,
           u2.username as approved_by_name,
           u3.username as received_by_name
    FROM stock_transfers st
    LEFT JOIN stores fs ON st.from_store_id = fs.id
    LEFT JOIN stores ts ON st.to_store_id = ts.id
    LEFT JOIN users u1 ON st.requested_by = u1.id
    LEFT JOIN users u2 ON st.approved_by = u2.id
    LEFT JOIN users u3 ON st.received_by = u3.id
    $where_clause
    ORDER BY st.created_at DESC
";

if ($params) {
    $stmt = $conn->prepare($transfers_query);
    $stmt->bind_param($param_types, ...$params);
    $stmt->execute();
    $transfers_result = $stmt->get_result();
    $stmt->close();
} else {
    $transfers_result = $conn->query($transfers_query);
}

// Get stores for filter
$stores_query = "SELECT * FROM stores WHERE is_active = 1 ORDER BY store_name";
$stores_result = $conn->query($stores_query);
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header d-flex justify-content-between align-items-center">
            <div class="page-title">
                <h4>Stock Transfer Management</h4>
                <h6>Approve and manage stock transfers between stores</h6>
            </div>
            <div class="d-flex gap-2">
                <a href="stock_transfer_request.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> New Transfer Request
                </a>
            </div>
        </div>

        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php 
                if ($_GET['success'] == 1) echo "Transfer approved successfully!";
                elseif ($_GET['success'] == 2) echo "Transfer rejected successfully!";
                elseif ($_GET['success'] == 3) echo "Transfer marked as in transit!";
                elseif ($_GET['success'] == 4) echo "Transfer received successfully!";
                ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Filters -->
        <div class="card">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control">
                            <option value="">All Status</option>
                            <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="approved" <?= $status_filter === 'approved' ? 'selected' : '' ?>>Approved</option>
                            <option value="in_transit" <?= $status_filter === 'in_transit' ? 'selected' : '' ?>>In Transit</option>
                            <option value="received" <?= $status_filter === 'received' ? 'selected' : '' ?>>Received</option>
                            <option value="cancelled" <?= $status_filter === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Store</label>
                        <select name="store_id" class="form-control">
                            <option value="">All Stores</option>
                            <?php while ($store = $stores_result->fetch_assoc()): ?>
                                <option value="<?= $store['id'] ?>" <?= $store_filter == $store['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($store['store_name']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">&nbsp;</label>
                        <div>
                            <button type="submit" class="btn btn-primary">Filter</button>
                            <a href="stock_transfer_approval.php" class="btn btn-secondary">Clear</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- Transfers List -->
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table datanew">
                        <thead>
                            <tr>
                                <th>Transfer #</th>
                                <th>From Store</th>
                                <th>To Store</th>
                                <th>Items</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($transfer = $transfers_result->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <strong><?= htmlspecialchars($transfer['transfer_number']) ?></strong>
                                        <br><small class="text-muted"><?= htmlspecialchars($transfer['notes']) ?></small>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-store text-danger me-2"></i>
                                            <div>
                                                <strong><?= htmlspecialchars($transfer['from_store_name']) ?></strong>
                                                <br><small class="text-muted"><?= htmlspecialchars($transfer['from_store_code']) ?></small>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-store text-success me-2"></i>
                                            <div>
                                                <strong><?= htmlspecialchars($transfer['to_store_name']) ?></strong>
                                                <br><small class="text-muted"><?= htmlspecialchars($transfer['to_store_code']) ?></small>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge bg-info"><?= $transfer['total_items'] ?> items</span>
                                        <br><small class="text-muted"><?= number_format($transfer['total_quantity'], 2) ?> units</small>
                                    </td>
                                    <td>
                                        <?php
                                        $status_class = '';
                                        $status_text = '';
                                        switch ($transfer['status']) {
                                            case 'pending':
                                                $status_class = 'bg-warning';
                                                $status_text = 'Pending';
                                                break;
                                            case 'approved':
                                                $status_class = 'bg-info';
                                                $status_text = 'Approved';
                                                break;
                                            case 'in_transit':
                                                $status_class = 'bg-primary';
                                                $status_text = 'In Transit';
                                                break;
                                            case 'received':
                                                $status_class = 'bg-success';
                                                $status_text = 'Received';
                                                break;
                                            case 'cancelled':
                                                $status_class = 'bg-danger';
                                                $status_text = 'Cancelled';
                                                break;
                                        }
                                        ?>
                                        <span class="badge <?= $status_class ?>"><?= $status_text ?></span>
                                    </td>
                                    <td>
                                        <div>
                                            <strong><?= date('M d, Y', strtotime($transfer['transfer_date'])) ?></strong>
                                            <br><small class="text-muted"><?= date('h:i A', strtotime($transfer['transfer_date'])) ?></small>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="d-flex gap-1">
                                            <button type="button" class="btn btn-sm btn-outline-info" 
                                                    onclick="viewTransfer(<?= $transfer['id'] ?>)">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            
                                            <?php if ($transfer['status'] === 'pending'): ?>
                                                <form method="POST" style="display: inline;">
                                                    <input type="hidden" name="action" value="approve_transfer">
                                                    <input type="hidden" name="transfer_id" value="<?= $transfer['id'] ?>">
                                                    <button type="submit" class="btn btn-sm btn-success" onclick="return confirm('Approve this transfer?')">
                                                        <i class="fas fa-check"></i>
                                                    </button>
                                                </form>
                                                <form method="POST" style="display: inline;">
                                                    <input type="hidden" name="action" value="reject_transfer">
                                                    <input type="hidden" name="transfer_id" value="<?= $transfer['id'] ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Reject this transfer?')">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </form>
                                            <?php elseif ($transfer['status'] === 'approved'): ?>
                                                <form method="POST" style="display: inline;">
                                                    <input type="hidden" name="action" value="mark_in_transit">
                                                    <input type="hidden" name="transfer_id" value="<?= $transfer['id'] ?>">
                                                    <button type="submit" class="btn btn-sm btn-primary" onclick="return confirm('Mark as in transit?')">
                                                        <i class="fas fa-truck"></i>
                                                    </button>
                                                </form>
                                            <?php elseif ($transfer['status'] === 'in_transit'): ?>
                                                <form method="POST" style="display: inline;">
                                                    <input type="hidden" name="action" value="receive_transfer">
                                                    <input type="hidden" name="transfer_id" value="<?= $transfer['id'] ?>">
                                                    <button type="submit" class="btn btn-sm btn-success" onclick="return confirm('Receive this transfer? This will update inventory.')">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Transfer Details Modal -->
<div class="modal fade" id="transferDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Transfer Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="transferDetailsContent">
                <!-- Content will be loaded here -->
            </div>
        </div>
    </div>
</div>

<script>
function viewTransfer(transferId) {
    // Load transfer details via AJAX
    fetch(`ajax/get_transfer_details.php?transfer_id=${transferId}`)
        .then(response => response.text())
        .then(html => {
            document.getElementById('transferDetailsContent').innerHTML = html;
            new bootstrap.Modal(document.getElementById('transferDetailsModal')).show();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error loading transfer details');
        });
}
</script>
