<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    die("Unauthorized access");
}

// Validate input
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid request");
}

$deposit_id = intval($_GET['id']);

try {
    // Get deposit details
    $query = "SELECT cd.*, 
                     u.username as created_by_name,
                     COALESCE(cd.balance, cd.deposit - IFNULL(cd.refund_amount, 0)) as current_balance
              FROM container_deposit cd
              LEFT JOIN users u ON cd.user_id = u.user_id
              WHERE cd.id = ?";
              
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $deposit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result && $row = $result->fetch_assoc()) {
        // Format dates
        $date_deposited = $row['date_deposited'] ? date('Y-m-d', strtotime($row['date_deposited'])) : '-';
        $refund_date = $row['refund_date'] ? date('Y-m-d', strtotime($row['refund_date'])) : '-';
        $created_date = date('Y-m-d H:i', strtotime($row['created_date']));
        
        // Start building the HTML
        ?>
        <div class="row">
            <div class="col-md-6">
                <table class="table table-sm">
                    <tr>
                        <th width="40%">Shipping Line:</th>
                        <td><?php echo htmlspecialchars($row['shipping_line']); ?></td>
                    </tr>
                    <tr>
                        <th>Type:</th>
                        <td><span class="badge badge-<?php echo strtolower($row['type']); ?>"><?php echo ucfirst($row['type']); ?></span></td>
                    </tr>
                    <tr>
                        <th>BL Number:</th>
                        <td><?php echo htmlspecialchars($row['bl']); ?></td>
                    </tr>
                    <tr>
                        <th>Container:</th>
                        <td><?php echo htmlspecialchars($row['container']); ?></td>
                    </tr>
                    <tr>
                        <th>Date Deposited:</th>
                        <td><?php echo $date_deposited; ?></td>
                    </tr>
                </table>
            </div>
            <div class="col-md-6">
                <table class="table table-sm">
                    <tr>
                        <th width="40%">Deposit Amount:</th>
                        <td class="text-end">$<?php echo number_format($row['deposit'], 2); ?></td>
                    </tr>
                    <tr>
                        <th>Refund Amount:</th>
                        <td class="text-end">$<?php echo number_format($row['refund_amount'] ?? 0, 2); ?></td>
                    </tr>
                    <tr>
                        <th>Current Balance:</th>
                        <td class="text-end">$<?php echo number_format($row['current_balance'], 2); ?></td>
                    </tr>
                    <tr>
                        <th>Refund Date:</th>
                        <td><?php echo $refund_date; ?></td>
                    </tr>
                    <tr>
                        <th>Created By:</th>
                        <td><?php echo htmlspecialchars($row['created_by_name']); ?></td>
                    </tr>
                </table>
            </div>
        </div>

        <?php if (!empty($row['deposit_roll_over'])): ?>
        <div class="row mt-3">
            <div class="col-12">
                <h6 class="text-muted mb-2">Deposit Roll Over History</h6>
                <div class="card bg-light">
                    <div class="card-body">
                        <pre class="mb-0" style="white-space: pre-wrap;"><?php echo htmlspecialchars($row['deposit_roll_over']); ?></pre>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!empty($row['remarks'])): ?>
        <div class="row mt-3">
            <div class="col-12">
                <h6 class="text-muted mb-2">Remarks History</h6>
                <div class="card bg-light">
                    <div class="card-body">
                        <pre class="mb-0" style="white-space: pre-wrap;"><?php echo htmlspecialchars($row['remarks']); ?></pre>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (!empty($row['additional_info'])): ?>
        <div class="row mt-3">
            <div class="col-12">
                <h6 class="text-muted mb-2">Additional Information</h6>
                <div class="card bg-light">
                    <div class="card-body">
                        <pre class="mb-0" style="white-space: pre-wrap;"><?php echo htmlspecialchars($row['additional_info']); ?></pre>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php
        // Get refund history if any
        $query_refunds = "SELECT * FROM deposit_refund_log WHERE deposit_id = ? ORDER BY created_at DESC";
        $stmt = $conn->prepare($query_refunds);
        $stmt->bind_param("i", $deposit_id);
        $stmt->execute();
        $refund_result = $stmt->get_result();
        
        if ($refund_result && $refund_result->num_rows > 0): ?>
        <div class="row mt-3">
            <div class="col-12">
                <h6 class="text-muted mb-2">Refund History</h6>
                <table class="table table-sm table-striped">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Amount</th>
                            <th>Processed By</th>
                            <th>Remarks</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($refund = $refund_result->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo date('Y-m-d', strtotime($refund['refund_date'])); ?></td>
                            <td class="text-end">$<?php echo number_format($refund['refund_amount'], 2); ?></td>
                            <td>
                                <?php
                                $user_query = "SELECT username FROM users WHERE user_id = ?";
                                $user_stmt = $conn->prepare($user_query);
                                $user_stmt->bind_param("i", $refund['processed_by']);
                                $user_stmt->execute();
                                $user_result = $user_stmt->get_result();
                                echo $user_result->fetch_assoc()['username'] ?? 'Unknown';
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($refund['remarks']); ?></td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>

        <?php
    } else {
        echo '<div class="alert alert-danger">Container deposit record not found.</div>';
    }
    
} catch (Exception $e) {
    error_log("Error fetching deposit details: " . $e->getMessage());
    echo '<div class="alert alert-danger">Error loading deposit details. Please try again.</div>';
}
?>