<?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 has permission (admin or operations)
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Restrict access to admin and operations roles
if ($role_id != 1 && $role_id != 3) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

// Check if withdrawal ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No withdrawal ID provided";
    header('Location: cheque_withdrawals.php');
    exit();
}

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

// Format date helper function
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return 'N/A';
    }
    return date('Y-m-d', strtotime($date));
}

// Get withdrawal details
$sql = "
    SELECT 
        w.*,
        u1.full_name as requester_name,
        u2.full_name as approver_name
    FROM 
        cheque_withdrawals w
    LEFT JOIN 
        users u1 ON w.withdrawal_user_id = u1.user_id
    LEFT JOIN 
        users u2 ON w.approval_user_id = u2.user_id
    WHERE 
        w.id = ?
";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $withdrawal_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Withdrawal not found";
    header('Location: cheque_withdrawals.php');
    exit();
}

$withdrawal = $result->fetch_assoc();

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Cheque Withdrawal')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .detail-card {
            margin-bottom: 1.5rem;
        }
        .detail-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #e9e9ef;
            padding: 1rem;
        }
        .detail-label {
            font-weight: 600;
            margin-bottom: 5px;
            color: #495057;
        }
        .detail-value {
            margin-bottom: 15px;
        }
        .status-badge {
            padding: 0.5rem 1rem;
            font-size: 0.875rem;
            font-weight: 500;
            border-radius: 0.25rem;
        }
        .timeline {
            position: relative;
            padding-left: 30px;
            margin-top: 20px;
        }
        .timeline-item {
            position: relative;
            padding-bottom: 20px;
        }
        .timeline-item:last-child {
            padding-bottom: 0;
        }
        .timeline-item:before {
            content: '';
            position: absolute;
            left: -25px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e9e9ef;
        }
        .timeline-item .timeline-point {
            position: absolute;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #3085d6;
            left: -30px;
            top: 5px;
        }
        @media print {
            .no-print {
                display: none !important;
            }
            .card {
                border: none !important;
                box-shadow: none !important;
            }
            body {
                background-color: white !important;
            }
        }
    </style>
</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' => 'Finance Management', 'title' => 'View Cheque Withdrawal')); ?>

                    <?php
                    // Show success message if set
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">';
                        echo $_SESSION['success_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['success_message']);
                    }
                    
                    // Show error message if set
                    if (isset($_SESSION['error_message'])) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $_SESSION['error_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['error_message']);
                    }
                    ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="text-end no-print mb-3">
                                <a href="cheque_withdrawals.php" class="btn btn-secondary me-2">
                                    <i class="ri-arrow-left-line align-bottom"></i> Back
                                </a>
                                
                                <?php if ($withdrawal['status'] === 'pending'): ?>
                                    <?php if ($withdrawal['withdrawal_user_id'] == $user_id || $role_id == 1): ?>
                                    <a href="edit_withdrawal.php?id=<?php echo $withdrawal_id; ?>" class="btn btn-warning me-2">
                                        <i class="ri-edit-2-line align-bottom"></i> Edit
                                    </a>
                                    <?php endif; ?>
                                    
                                    <?php if ($role_id == 1): ?>
                                    <a href="approve_withdrawal.php?id=<?php echo $withdrawal_id; ?>" class="btn btn-success me-2">
                                        <i class="ri-check-double-line align-bottom"></i> Approve/Reject
                                    </a>
                                    <?php endif; ?>
                                <?php endif; ?>
                                
                                <button onclick="window.print()" class="btn btn-primary">
                                    <i class="ri-printer-line align-bottom"></i> Print
                                </button>
                            </div>
                            
                            <div class="card detail-card">
                                <div class="card-header detail-header d-flex justify-content-between align-items-center">
                                    <h4 class="card-title mb-0">Cheque Withdrawal #<?php echo $withdrawal_id; ?></h4>
                                    <?php
                                        $status = $withdrawal['status'];
                                        $status_class = 'bg-warning';
                                        
                                        if ($status === 'approved') {
                                            $status_class = 'bg-success';
                                        } elseif ($status === 'rejected') {
                                            $status_class = 'bg-danger';
                                        }
                                    ?>
                                    <span class="badge <?php echo $status_class; ?> status-badge"><?php echo ucfirst($status); ?></span>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="detail-label">Withdrawal Date</div>
                                            <div class="detail-value"><?php echo formatDate($withdrawal['withdrawal_date']); ?></div>
                                            
                                            <div class="detail-label">Amount</div>
                                            <div class="detail-value">
                                                <strong><?php echo $withdrawal['currency'] . ' ' . number_format($withdrawal['amount'], 2); ?></strong>
                                            </div>
                                            
                                            <div class="detail-label">Bank</div>
                                            <div class="detail-value"><?php echo $withdrawal['bank']; ?></div>
                                            
                                            <?php if (!empty($withdrawal['bank_branch'])): ?>
                                            <div class="detail-label">Bank Branch</div>
                                            <div class="detail-value"><?php echo $withdrawal['bank_branch']; ?></div>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($withdrawal['cheque_number'])): ?>
                                            <div class="detail-label">Cheque Number</div>
                                            <div class="detail-value"><?php echo $withdrawal['cheque_number']; ?></div>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="detail-label">Requested By</div>
                                            <div class="detail-value"><?php echo $withdrawal['requester_name']; ?></div>
                                            
                                            <div class="detail-label">Request Date</div>
                                            <div class="detail-value"><?php echo formatDate($withdrawal['created_at']); ?></div>
                                            
                                            <?php if ($withdrawal['status'] !== 'pending'): ?>
                                            <div class="detail-label">
                                                <?php echo $withdrawal['status'] === 'approved' ? 'Approved' : 'Rejected'; ?> By
                                            </div>
                                            <div class="detail-value"><?php echo $withdrawal['approver_name']; ?></div>
                                            
                                            <div class="detail-label">
                                                <?php echo $withdrawal['status'] === 'approved' ? 'Approval' : 'Rejection'; ?> Date
                                            </div>
                                            <div class="detail-value">
                                                <?php echo formatDate($withdrawal['status'] === 'approved' ? $withdrawal['approved_at'] : $withdrawal['rejected_at']); ?>
                                            </div>
                                            
                                            <?php if ($withdrawal['status'] === 'rejected' && !empty($withdrawal['rejection_reason'])): ?>
                                            <div class="detail-label">Rejection Reason</div>
                                            <div class="detail-value text-danger"><?php echo nl2br(htmlspecialchars($withdrawal['rejection_reason'])); ?></div>
                                            <?php endif; ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <div class="row mt-4">
                                        <div class="col-12">
                                            <div class="detail-label">Purpose</div>
                                            <div class="detail-value">
                                                <?php echo nl2br(htmlspecialchars($withdrawal['purpose'])); ?>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row mt-4 no-print">
                                        <div class="col-12">
                                            <h5 class="mb-3">Activity Timeline</h5>
                                            <div class="timeline">
                                                <div class="timeline-item">
                                                    <div class="timeline-point"></div>
                                                    <div class="timeline-content">
                                                        <div class="fw-bold">Request Created</div>
                                                        <div><?php echo formatDate($withdrawal['created_at']); ?></div>
                                                        <div class="text-muted">Requested by <?php echo $withdrawal['requester_name']; ?></div>
                                                    </div>
                                                </div>
                                                
                                                <?php if ($withdrawal['status'] !== 'pending'): ?>
                                                <div class="timeline-item">
                                                    <div class="timeline-point" style="background-color: <?php echo $withdrawal['status'] === 'approved' ? '#198754' : '#dc3545'; ?>"></div>
                                                    <div class="timeline-content">
                                                        <div class="fw-bold">
                                                            <?php echo $withdrawal['status'] === 'approved' ? 'Request Approved' : 'Request Rejected'; ?>
                                                        </div>
                                                        <div>
                                                            <?php echo formatDate($withdrawal['status'] === 'approved' ? $withdrawal['approved_at'] : $withdrawal['rejected_at']); ?>
                                                        </div>
                                                        <div class="text-muted">
                                                            <?php echo $withdrawal['status'] === 'approved' ? 'Approved' : 'Rejected'; ?> by <?php echo $withdrawal['approver_name']; ?>
                                                        </div>
                                                        <?php if ($withdrawal['status'] === 'rejected' && !empty($withdrawal['rejection_reason'])): ?>
                                                        <div class="mt-2 text-danger">
                                                            <strong>Reason:</strong> <?php echo nl2br(htmlspecialchars($withdrawal['rejection_reason'])); ?>
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <?php else: ?>
                                                <div class="timeline-item">
                                                    <div class="timeline-point" style="background-color: #ffc107"></div>
                                                    <div class="timeline-content">
                                                        <div class="fw-bold">Pending Approval</div>
                                                        <div class="text-muted">Waiting for administrator approval</div>
                                                    </div>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="text-center mt-4 mb-4 d-print-block d-none">
                                <p>This document was generated from <?php echo $system_name; ?> on <?php echo date('Y-m-d H:i:s'); ?></p>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Show success message with SweetAlert if present
            <?php if (isset($_SESSION['swal_success'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: '<?php echo $_SESSION['swal_success']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_success']); endif; ?>
            
            // Show error message with SweetAlert if present
            <?php if (isset($_SESSION['swal_error'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: '<?php echo $_SESSION['swal_error']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_error']); endif; ?>
        });
    </script>

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