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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if user is Accountant
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Accountant') {
    header('Location: index.php');
    exit();
}

// Current Month Revenue
$current_month = date('Y-m');
$sql_revenue = "SELECT SUM(amount) as total FROM rent_payments 
                WHERE payment_status = 'COMPLETED' 
                AND DATE_FORMAT(payment_date, '%Y-%m') = ?";
$stmt_rev = $conn->prepare($sql_revenue);
$stmt_rev->bind_param("s", $current_month);
$stmt_rev->execute();
$result_rev = $stmt_rev->get_result();
$monthly_revenue = $result_rev->fetch_assoc()['total'] ?? 0;

// Current Month Expenses
$sql_expenses = "SELECT SUM(amount) as total FROM expenses 
                 WHERE status = 'paid' 
                 AND DATE_FORMAT(incurred_date, '%Y-%m') = ?";
$stmt_exp = $conn->prepare($sql_expenses);
$stmt_exp->bind_param("s", $current_month);
$stmt_exp->execute();
$result_exp = $stmt_exp->get_result();
$monthly_expenses = $result_exp->fetch_assoc()['total'] ?? 0;

// Net Profit
$net_profit = $monthly_revenue - $monthly_expenses;

// Outstanding Invoices
$sql_outstanding = "SELECT COUNT(*) as total, SUM(balance) as total_balance
                    FROM invoices 
                    WHERE status IN ('unpaid', 'overdue', 'partial')";
$result_outstanding = $conn->query($sql_outstanding);
$outstanding = $result_outstanding->fetch_assoc();
$outstanding_count = $outstanding['total'] ?? 0;
$outstanding_balance = $outstanding['total_balance'] ?? 0;

// Recent Payments
$sql_recent_payments = "SELECT rp.*, l.lease_code, u.unit_number, p.name as property_name
                        FROM rent_payments rp
                        JOIN leases l ON rp.lease_id = l.id
                        JOIN units u ON l.unit_id = u.id
                        JOIN properties p ON u.property_id = p.id
                        WHERE rp.payment_status = 'COMPLETED'
                        ORDER BY rp.payment_date DESC LIMIT 10";
$result_recent_payments = $conn->query($sql_recent_payments);

// Recent Expenses
$sql_recent_expenses = "SELECT e.*, p.name as property_name
                        FROM expenses e
                        LEFT JOIN properties p ON e.property_id = p.id
                        WHERE e.status = 'paid'
                        ORDER BY e.incurred_date DESC LIMIT 10";
$result_recent_expenses = $conn->query($sql_recent_expenses);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Accountant Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
</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' => 'Dashboard', 'title' => 'Accountant Dashboard')); ?>

                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Monthly Revenue</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-success rounded-circle fs-3">
                                                    <i class="ri-arrow-up-line text-success"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($monthly_revenue, 0); ?>
                                            </h4>
                                            <a href="list_payments.php" class="text-decoration-underline">View payments</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Monthly Expenses</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-danger rounded-circle fs-3">
                                                    <i class="ri-arrow-down-line text-danger"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($monthly_expenses, 0); ?>
                                            </h4>
                                            <a href="list_expenses.php" class="text-decoration-underline">View expenses</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Net Profit</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-<?php echo $net_profit >= 0 ? 'success' : 'danger'; ?> rounded-circle fs-3">
                                                    <i class="ri-line-chart-line text-<?php echo $net_profit >= 0 ? 'success' : 'danger'; ?>"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($net_profit, 0); ?>
                                            </h4>
                                            <a href="report_pnl.php" class="text-decoration-underline">View P&L</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Outstanding</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-warning rounded-circle fs-3">
                                                    <i class="ri-alert-line text-warning"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($outstanding_balance, 0); ?>
                                            </h4>
                                            <span class="badge bg-soft-warning text-warning mb-0">
                                                <?php echo $outstanding_count; ?> invoices
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Recent Payments</h4>
                                    <a href="list_payments.php" class="btn btn-soft-primary btn-sm">View All</a>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Property/Unit</th>
                                                    <th>Lease</th>
                                                    <th>Amount</th>
                                                    <th>Method</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_recent_payments && $result_recent_payments->num_rows > 0): ?>
                                                    <?php while($payment = $result_recent_payments->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($payment['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($payment['unit_number']); ?></p>
                                                                </div>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($payment['lease_code']); ?></td>
                                                            <td>
                                                                <span class="fw-semibold text-success">KES <?php echo number_format($payment['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info"><?php echo htmlspecialchars($payment['payment_method']); ?></span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center py-4">
                                                            <div class="text-muted">No payments found</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Recent Expenses</h4>
                                    <a href="list_expenses.php" class="btn btn-soft-primary btn-sm">View All</a>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Property</th>
                                                    <th>Category</th>
                                                    <th>Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_recent_expenses && $result_recent_expenses->num_rows > 0): ?>
                                                    <?php while($expense = $result_recent_expenses->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($expense['incurred_date'])); ?></td>
                                                            <td><?php echo htmlspecialchars($expense['property_name'] ?? 'N/A'); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-info"><?php echo htmlspecialchars($expense['category']); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold text-danger">KES <?php echo number_format($expense['amount'], 2); ?></span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="4" class="text-center py-4">
                                                            <div class="text-muted">No expenses found</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

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