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

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

// Get user details and role
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id 
                     FROM users WHERE user_id = ?";
$stmt = $conn->prepare($sql_user_details);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result_user_details = $stmt->get_result();

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $role_id = $row_user_details['role_id'];
} else {
    header('Location: login.php');
    exit();
}

// Check if expense ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $_SESSION['error_message'] = "Invalid expense ID";
    header('Location: expense_list.php');
    exit();
}

$expense_id = (int)$_GET['id'];

// Fetch expense details with related information
$sql = "SELECT e.*, 
        u1.full_name as created_by_name,
        u2.full_name as approved_by_name,
        u3.full_name as rejected_by_name,
        e.description as expense_code_desc
        FROM expenses e
        LEFT JOIN users u1 ON e.user_id = u1.user_id
        LEFT JOIN users u2 ON e.user_id = u2.user_id
        LEFT JOIN users u3 ON e.user_id = u3.user_id
        WHERE e.id = ?";

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

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

$expense = $result->fetch_assoc();

// Check if user can approve/reject
$can_approve = in_array($role_id, [1, 2, 3]) && $expense['status'] === 'Pending';
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Expense')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .expense-header {
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 1rem;
            color: #495057;
        }
        .expense-label {
            font-weight: 500;
            color: #74788d;
            min-width: 150px;
        }
        .expense-value {
            color: #495057;
        }
        .status-badge {
            padding: 6px 12px;
            border-radius: 4px;
            font-weight: 500;
            display: inline-block;
        }
        .status-pending { 
            background-color: #fff3cd; 
            color: #856404; 
        }
        .status-approved { 
            background-color: #d4edda; 
            color: #155724; 
        }
        .status-rejected { 
            background-color: #f8d7da; 
            color: #721c24; 
        }
        .detail-card {
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 0 10px rgba(0,0,0,0.05);
            margin-bottom: 1rem;
        }
        .detail-card .card-body {
            padding: 1.25rem;
        }
        .info-row {
            display: flex;
            margin-bottom: 1rem;
            padding: 0.5rem 0;
            border-bottom: 1px solid #f1f1f1;
        }
        .info-row:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }
        .timeline {
            position: relative;
            padding: 1rem 0;
        }
        .timeline-item {
            position: relative;
            padding-left: 2rem;
            margin-bottom: 1.5rem;
        }
        .timeline-item:before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            border-left: 2px solid #e9ecef;
        }
        .timeline-item:last-child:before {
            height: 50%;
        }
        .timeline-point {
            position: absolute;
            left: -5px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #556ee6;
            top: 4px;
        }
        .timeline-date {
            font-size: 0.85rem;
            color: #74788d;
            margin-bottom: 0.25rem;
        }
        .action-buttons .btn {
            margin-left: 0.5rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Expenses', 'title' => 'View Expense')); ?>

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

                    <div class="row">
                        <div class="col-lg-12">
                            <!-- Header Card -->
                            <div class="card mb-4">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h4 class="card-title mb-0">
                                                Expense Details - <?php echo htmlspecialchars($expense['exp_no']); ?>
                                            </h4>
                                            <span class="text-muted">Created on <?php echo date('d M Y', strtotime($expense['created_date'])); ?></span>
                                        </div>
                                        <div class="action-buttons">
                                            <button class="btn btn-light btn-sm" id="btnPrint">
                                                <i class="ri-printer-line me-1"></i> Print
                                            </button>
                                            <a href="expense_list.php" class="btn btn-secondary btn-sm">
                                                <i class="ri-arrow-left-line me-1"></i> Back
                                            </a>
                                            <?php if ($can_approve): ?>
                                                <button type="button" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#approveModal">
                                                    <i class="ri-check-line me-1"></i> Approve
                                                </button>
                                                <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#rejectModal">
                                                    <i class="ri-close-line me-1"></i> Reject
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Main Details -->
                            <div class="row">
                                <!-- Left Column -->
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-body">
                                            <h5 class="card-title mb-4">Basic Information</h5>
                                            
                                            <div class="info-row">
                                                <span class="expense-label">Status</span>
                                                <span class="status-badge status-<?php echo strtolower($expense['status']); ?>">
                                                    <?php echo htmlspecialchars($expense['status']); ?>
                                                </span>
                                            </div>
                                            
                                            <div class="info-row">
                                                <span class="expense-label">Amount</span>
                                                <span class="expense-value">
                                                    <?php echo htmlspecialchars($expense['currency']); ?> 
                                                    <?php echo number_format($expense['amount'], 2); ?>
                                                </span>
                                            </div>
                                            
                                            <div class="info-row">
                                                <span class="expense-label">Office Cost</span>
                                                <span class="expense-value">
                                                    <?php echo htmlspecialchars($expense['office_cost']); ?>
                                                </span>
                                            </div>
                                            
                                            <div class="info-row">
                                                <span class="expense-label">Expense Code</span>
                                                <span class="expense-value">
                                                    <?php echo htmlspecialchars($expense['expense_code']); ?>
                                                    <?php if (!empty($expense['expense_code_desc'])): ?>
                                                        - <?php echo htmlspecialchars($expense['expense_code_desc']); ?>
                                                    <?php endif; ?>
                                                </span>
                                            </div>
                                            
                                            <div class="info-row">
                                                <span class="expense-label">Payment Mode</span>
                                                <span class="expense-value">
                                                    <?php echo htmlspecialchars($expense['pay_mode']); ?>
                                                </span>
                                            </div>
                                            
                                            <?php if (!empty($expense['file_number'])): ?>
                                                <div class="info-row">
                                                    <span class="expense-label">File Number</span>
                                                    <span class="expense-value">
                                                        <?php echo htmlspecialchars($expense['file_number']); ?>
                                                    </span>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>

                                <!-- Right Column -->
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-body">
                                            <h5 class="card-title mb-4">Description & Details</h5>
                                            
                                            <div class="info-row">
                                                <span class="expense-label">Description</span>
                                                <span class="expense-value">
                                                    <?php echo nl2br(htmlspecialchars($expense['description'])); ?>
                                                </span>
                                            </div>

                                            <!-- Timeline -->
                                            <div class="timeline mt-4">
                                                <div class="timeline-item">
                                                    <div class="timeline-point"></div>
                                                    <div class="timeline-content">
                                                        <div class="timeline-date">
                                                            <?php echo date('d M Y H:i', strtotime($expense['created_date'])); ?>
                                                        </div>
                                                        <strong>Created by </strong>
                                                        <?php echo htmlspecialchars($expense['created_by_name']); ?>
                                                    </div>
                                                </div>

                                                <?php if ($expense['status'] === 'Approved'): ?>
                                                    <div class="timeline-item">
                                                        <div class="timeline-point bg-success"></div>
                                                        <div class="timeline-content">
                                                            <div class="timeline-date">
                                                                <?php echo date('d M Y H:i', strtotime($expense['approved_date'])); ?>
                                                            </div>
                                                            <strong>Approved by </strong>
                                                            <?php echo htmlspecialchars($expense['approved_by_name']); ?>
                                                        </div>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if ($expense['status'] === 'Rejected'): ?>
                                                    <div class="timeline-item">
                                                        <div class="timeline-point bg-danger"></div>
                                                        <div class="timeline-content">
                                                            <div class="timeline-date">
                                                                <?php echo date('d M Y H:i', strtotime($expense['rejected_date'])); ?>
                                                            </div>
                                                            <strong>Rejected by </strong>
                                                            <?php echo htmlspecialchars($expense['rejected_by_name']); ?>
                                                            <?php if (!empty($expense['rejection_reason'])): ?>
                                                                <div class="mt-2 text-danger">
                                                                    <strong>Reason: </strong>
                                                                    <?php echo nl2br(htmlspecialchars($expense['rejection_reason'])); ?>
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Approve Modal -->
    <div class="modal fade" id="approveModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Approve Expense</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to approve this expense?</p>
                    <div class="alert alert-info">
                        <strong>Expense No:</strong> <?php echo htmlspecialchars($expense['exp_no']); ?><br>
                        <strong>Amount:</strong> <?php echo $expense['currency'] . ' ' . number_format($expense['amount'], 2); ?>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <a href="approve_expense.php?id=<?php echo $expense_id; ?>" class="btn btn-success">
                        Approve Expense
                    </a>
                </div>
            </div>
        </div>
    </div>
    <!-- After the Approve Modal -->

<!-- Reject Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Reject Expense</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="reject_expense.php" method="POST">
                <div class="modal-body">
                    <input type="hidden" name="expense_id" value="<?php echo $expense_id; ?>">
                    <div class="alert alert-warning">
                        <strong>Expense No:</strong> <?php echo htmlspecialchars($expense['exp_no']); ?><br>
                        <strong>Amount:</strong> <?php echo $expense['currency'] . ' ' . number_format($expense['amount'], 2); ?>
                    </div>
                    <div class="mb-3">
                        <label for="rejection_reason" class="form-label">Reason for Rejection</label>
                        <textarea class="form-control" id="rejection_reason" name="rejection_reason" rows="3" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Reject Expense</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Print Section (hidden) -->
<div id="printSection" style="display: none;">
    <div style="padding: 20px;">
        <div style="text-align: center; margin-bottom: 20px;">
            <h2>Expense Details</h2>
            <h3><?php echo htmlspecialchars($expense['exp_no']); ?></h3>
        </div>
        
        <table style="width: 100%; margin-bottom: 20px;">
            <tr>
                <td style="width: 150px;"><strong>Status:</strong></td>
                <td><?php echo htmlspecialchars($expense['status']); ?></td>
            </tr>
            <tr>
                <td><strong>Amount:</strong></td>
                <td><?php echo $expense['currency'] . ' ' . number_format($expense['amount'], 2); ?></td>
            </tr>
            <tr>
                <td><strong>Office Cost:</strong></td>
                <td><?php echo htmlspecialchars($expense['office_cost']); ?></td>
            </tr>
            <tr>
                <td><strong>Payment Mode:</strong></td>
                <td><?php echo htmlspecialchars($expense['pay_mode']); ?></td>
            </tr>
            <tr>
                <td><strong>Created By:</strong></td>
                <td><?php echo htmlspecialchars($expense['created_by_name']); ?></td>
            </tr>
            <tr>
                <td><strong>Created Date:</strong></td>
                <td><?php echo date('d M Y H:i', strtotime($expense['created_date'])); ?></td>
            </tr>
            <?php if (!empty($expense['file_number'])): ?>
            <tr>
                <td><strong>File Number:</strong></td>
                <td><?php echo htmlspecialchars($expense['file_number']); ?></td>
            </tr>
            <?php endif; ?>
        </table>

        <div style="margin-bottom: 20px;">
            <h4>Description</h4>
            <p><?php echo nl2br(htmlspecialchars($expense['description'])); ?></p>
        </div>

        <?php if ($expense['status'] === 'Approved'): ?>
        <div style="margin-bottom: 20px;">
            <h4>Approval Details</h4>
            <p>
                Approved by: <?php echo htmlspecialchars($expense['approved_by_name']); ?><br>
                Date: <?php echo date('d M Y H:i', strtotime($expense['approved_date'])); ?>
            </p>
        </div>
        <?php endif; ?>

        <?php if ($expense['status'] === 'Rejected'): ?>
        <div style="margin-bottom: 20px;">
            <h4>Rejection Details</h4>
            <p>
                Rejected by: <?php echo htmlspecialchars($expense['rejected_by_name']); ?><br>
                Date: <?php echo date('d M Y H:i', strtotime($expense['rejected_date'])); ?><br>
                Reason: <?php echo nl2br(htmlspecialchars($expense['rejection_reason'])); ?>
            </p>
        </div>
        <?php endif; ?>
    </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Print functionality
    document.getElementById('btnPrint').addEventListener('click', function() {
        const printContent = document.getElementById('printSection').innerHTML;
        const originalContent = document.body.innerHTML;

        document.body.innerHTML = printContent;
        window.print();
        document.body.innerHTML = originalContent;
        
        // Reinitialize event listeners and scripts
        location.reload();
    });
});
</script>

</body>
</html>