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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is admin
$user_id = $_SESSION['user_id'];
$sql_user_role = "SELECT role_id FROM users WHERE user_id = $user_id";
$result_user_role = $conn->query($sql_user_role);
$is_admin = false;

if ($result_user_role && $row_user_role = $result_user_role->fetch_assoc()) {
    $role_id = $row_user_role['role_id'];
    $is_admin = ($role_id == 1); // Assuming role_id 1 is admin
}

if (!$is_admin) {
    $_SESSION['error_message'] = "Access denied. Only administrators can access this page.";
    header('Location: index.php');
    exit();
}

// Process approval/rejection if submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && isset($_POST['id'])) {
    $id = (int)$_POST['id'];
    $action = $_POST['action'];
    $admin_remarks = $_POST['admin_remarks'] ?? '';
    
    try {
        // Begin transaction
        $conn->begin_transaction();
        
        if ($action === 'approve') {
            // Update status to Approved
            $query_update = "UPDATE container_deposit 
                            SET status = 'Approved', 
                                admin_remarks = ?,
                                approved_by = ?,
                                approved_at = NOW() 
                            WHERE id = ?";
            
            $stmt_update = $conn->prepare($query_update);
            $stmt_update->bind_param("sii", $admin_remarks, $user_id, $id);
            
            if (!$stmt_update->execute()) {
                throw new Exception("Failed to update deposit record: " . $stmt_update->error);
            }
            
            $_SESSION['success_message'] = "Refund request has been approved successfully.";
        } 
        elseif ($action === 'reject') {
            // Get current deposit information to revert the refund
            $query_current = "SELECT deposit, refund_amount FROM container_deposit WHERE id = ?";
            $stmt_current = $conn->prepare($query_current);
            $stmt_current->bind_param("i", $id);
            $stmt_current->execute();
            $result_current = $stmt_current->get_result();
            
            if (!$row_current = $result_current->fetch_assoc()) {
                throw new Exception("Container deposit record not found.");
            }
            
            $deposit_amount = $row_current['deposit'];
            $refund_amount = $row_current['refund_amount'] ?? 0;
            
            // Reset refund information and update status
            $query_update = "UPDATE container_deposit 
                            SET refund_amount = 0, 
                                refund_date = NULL, 
                                balance = deposit,
                                status = 'Rejected', 
                                admin_remarks = ?,
                                approved_by = ?,
                                approved_at = NOW() 
                            WHERE id = ?";
            
            $stmt_update = $conn->prepare($query_update);
            $stmt_update->bind_param("sii", $admin_remarks, $user_id, $id);
            
            if (!$stmt_update->execute()) {
                throw new Exception("Failed to update deposit record: " . $stmt_update->error);
            }
            
            $_SESSION['success_message'] = "Refund request has been rejected.";
        }
        
        // Commit transaction
        $conn->commit();
        
        header('Location: refund_approvals.php');
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction on error
        if ($conn->connect_errno == 0) {
            $conn->rollback();
        }
        
        $_SESSION['error_message'] = "Error: " . $e->getMessage();
        header('Location: refund_approvals.php');
        exit();
    }
}

// Fetch pending refund requests
$query = "SELECT cd.id, cd.bl, cd.shipping_line, cd.container, cd.type, 
                 cd.deposit, cd.date_deposited, cd.refund_amount, cd.balance, 
                 cd.refund_date, cd.remarks, cd.status,
                 u.full_name as requested_by, cd.created_at
          FROM container_deposit cd
          LEFT JOIN users u ON cd.created_by = u.user_id
          WHERE cd.status = 'Pending' AND cd.refund_amount > 0
          ORDER BY cd.created_at DESC";

$result = $conn->query($query);
$pending_refunds = [];

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $pending_refunds[] = $row;
    }
}

// Set system name from settings
$sql = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $system_name = $row['setting_value'];
} else {
    $system_name = "Royal Freight"; // Fallback if not found
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Refund Approval')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">

        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Container Deposit', 'title' => 'Refund Approvals')); ?>

                    <!-- Alert for messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h4 class="card-title mb-0">Pending Refund Requests</h4>
                                    <a href="container_depo_list.php" class="btn btn-primary btn-sm">
                                        <i class="ri-arrow-left-line"></i> Back to List
                                    </a>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($pending_refunds)): ?>
                                        <div class="text-center py-5">
                                            <div class="avatar-md mx-auto mb-4">
                                                <div class="avatar-title rounded-circle bg-light text-primary">
                                                    <i class="ri-check-double-line fs-24"></i>
                                                </div>
                                            </div>
                                            <h5 class="text-muted">No pending refund requests</h5>
                                            <p class="text-muted mb-0">All refund requests have been processed</p>
                                        </div>
                                    <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-hover table-nowrap mb-0">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th scope="col">BL Number</th>
                                                        <th scope="col">Container</th>
                                                        <th scope="col">Shipping Line</th>
                                                        <th scope="col">Deposit Amount</th>
                                                        <th scope="col">Refund Amount</th>
                                                        <th scope="col">Refund Date</th>
                                                        <th scope="col">Requested By</th>
                                                        <th scope="col">Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($pending_refunds as $refund): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($refund['bl']); ?></td>
                                                            <td><?php echo htmlspecialchars($refund['container']); ?></td>
                                                            <td><?php echo htmlspecialchars($refund['shipping_line']); ?></td>
                                                            <td>$<?php echo number_format($refund['deposit'], 2); ?></td>
                                                            <td class="text-primary">$<?php echo number_format($refund['refund_amount'], 2); ?></td>
                                                            <td><?php echo date('Y-m-d', strtotime($refund['refund_date'])); ?></td>
                                                            <td><?php echo htmlspecialchars($refund['requested_by']); ?></td>
                                                            <td>
                                                                <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#viewModal<?php echo $refund['id']; ?>">
                                                                    <i class="ri-eye-line"></i> View
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <!-- Modals for each refund request -->
    <?php foreach ($pending_refunds as $refund): ?>
    <div class="modal fade" id="viewModal<?php echo $refund['id']; ?>" tabindex="-1" aria-labelledby="viewModalLabel<?php echo $refund['id']; ?>" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewModalLabel<?php echo $refund['id']; ?>">Refund Request Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h6 class="fw-semibold">Bill of Lading (BL)</h6>
                            <p><?php echo htmlspecialchars($refund['bl']); ?></p>
                        </div>
                        <div class="col-md-6">
                            <h6 class="fw-semibold">Container Number</h6>
                            <p><?php echo htmlspecialchars($refund['container']); ?></p>
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h6 class="fw-semibold">Shipping Line</h6>
                            <p><?php echo htmlspecialchars($refund['shipping_line']); ?></p>
                        </div>
                        <div class="col-md-6">
                            <h6 class="fw-semibold">Type</h6>
                            <p><?php echo htmlspecialchars($refund['type']); ?></p>
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <h6 class="fw-semibold">Deposit Amount</h6>
                            <p class="text-dark">$<?php echo number_format($refund['deposit'], 2); ?></p>
                        </div>
                        <div class="col-md-4">
                            <h6 class="fw-semibold">Refund Amount</h6>
                            <p class="text-primary">$<?php echo number_format($refund['refund_amount'], 2); ?></p>
                        </div>
                        <div class="col-md-4">
                            <h6 class="fw-semibold">Remaining Balance</h6>
                            <p class="text-muted">$<?php echo number_format($refund['balance'], 2); ?></p>
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <h6 class="fw-semibold">Date Deposited</h6>
                            <p><?php echo date('Y-m-d', strtotime($refund['date_deposited'])); ?></p>
                        </div>
                        <div class="col-md-4">
                            <h6 class="fw-semibold">Refund Date</h6>
                            <p><?php echo date('Y-m-d', strtotime($refund['refund_date'])); ?></p>
                        </div>
                        <div class="col-md-4">
                            <h6 class="fw-semibold">Requested By</h6>
                            <p><?php echo htmlspecialchars($refund['requested_by']); ?></p>
                        </div>
                    </div>
                    
                    <?php if (!empty($refund['remarks'])): ?>
                    <div class="row mb-4">
                        <div class="col-12">
                            <h6 class="fw-semibold">Remarks</h6>
                            <p><?php echo nl2br(htmlspecialchars($refund['remarks'])); ?></p>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <form method="POST" action="refund_approvals.php">
                        <input type="hidden" name="id" value="<?php echo $refund['id']; ?>">
                        
                        <div class="row mb-3">
                            <div class="col-12">
                                <label for="admin_remarks" class="form-label">Admin Remarks</label>
                                <textarea class="form-control" id="admin_remarks" name="admin_remarks" rows="3"></textarea>
                            </div>
                        </div>
                        
                        <div class="d-flex justify-content-end">
                            <button type="submit" name="action" value="reject" class="btn btn-danger me-2">
                                <i class="ri-close-circle-line"></i> Reject
                            </button>
                            <button type="submit" name="action" value="approve" class="btn btn-success">
                                <i class="ri-check-line"></i> Approve
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>

    <?php include 'layouts/vendor-scripts.php'; ?>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>