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

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

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

$user_id = $_SESSION['user_id'];

// Get tenant ID
$sql_tenant = "SELECT tenant_id FROM tenants WHERE user_id = ?";
$stmt_tenant = $conn->prepare($sql_tenant);
$stmt_tenant->bind_param("i", $user_id);
$stmt_tenant->execute();
$result_tenant = $stmt_tenant->get_result();
$tenant = $result_tenant->fetch_assoc();

if (!$tenant) {
    header('Location: login.php');
    exit();
}

$tenant_id = $tenant['tenant_id'];

// Get active lease
$sql_lease = "SELECT l.*, u.unit_number, p.name as property_name, p.location_area
              FROM leases l
              JOIN units u ON l.unit_id = u.id
              JOIN properties p ON u.property_id = p.id
              JOIN lease_tenants lt ON l.id = lt.lease_id AND lt.is_primary = 1
              WHERE lt.tenant_id = ? AND l.lease_status = 'ACTIVE'
              ORDER BY l.start_date DESC LIMIT 1";
$stmt_lease = $conn->prepare($sql_lease);
$stmt_lease->bind_param("i", $tenant_id);
$stmt_lease->execute();
$result_lease = $stmt_lease->get_result();
$lease = $result_lease->fetch_assoc();

// Outstanding Invoices
$sql_outstanding = "SELECT COUNT(*) as total, SUM(balance) as total_balance
                    FROM invoices i
                    JOIN leases l ON i.lease_id = l.id
                    JOIN lease_tenants lt ON l.id = lt.lease_id AND lt.is_primary = 1
                    WHERE lt.tenant_id = ? 
                    AND i.status IN ('unpaid', 'overdue', 'partial')";
$stmt_outstanding = $conn->prepare($sql_outstanding);
$stmt_outstanding->bind_param("i", $tenant_id);
$stmt_outstanding->execute();
$result_outstanding = $stmt_outstanding->get_result();
$outstanding = $result_outstanding->fetch_assoc();
$outstanding_count = $outstanding['total'] ?? 0;
$outstanding_balance = $outstanding['total_balance'] ?? 0;

// Recent Payments
$sql_payments = "SELECT COUNT(*) as total, SUM(amount) as total_paid
                 FROM rent_payments rp
                 JOIN leases l ON rp.lease_id = l.id
                 JOIN lease_tenants lt ON l.id = lt.lease_id AND lt.is_primary = 1
                 WHERE lt.tenant_id = ? 
                 AND rp.payment_status = 'COMPLETED'
                 AND DATE_FORMAT(rp.payment_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m')";
$stmt_payments = $conn->prepare($sql_payments);
$stmt_payments->bind_param("i", $tenant_id);
$stmt_payments->execute();
$result_payments = $stmt_payments->get_result();
$payments = $result_payments->fetch_assoc();
$monthly_payments = $payments['total'] ?? 0;
$monthly_paid = $payments['total_paid'] ?? 0;

// Pending Maintenance Requests
$sql_maint = "SELECT COUNT(*) as total FROM maintenance_requests 
              WHERE tenant_id = ? AND status IN ('Open', 'NEW', 'Assigned')";
$stmt_maint = $conn->prepare($sql_maint);
$stmt_maint->bind_param("i", $tenant_id);
$stmt_maint->execute();
$result_maint = $stmt_maint->get_result();
$pending_maintenance = $result_maint->fetch_assoc()['total'] ?? 0;

// Recent Invoices
$sql_recent_invoices = "SELECT i.*, l.lease_code, u.unit_number, p.name as property_name
                        FROM invoices i
                        JOIN leases l ON i.lease_id = l.id
                        JOIN units u ON l.unit_id = u.id
                        JOIN properties p ON u.property_id = p.id
                        JOIN lease_tenants lt ON l.id = lt.lease_id AND lt.is_primary = 1
                        WHERE lt.tenant_id = ?
                        ORDER BY i.due_date DESC LIMIT 5";
$stmt_invoices = $conn->prepare($sql_recent_invoices);
$stmt_invoices->bind_param("i", $tenant_id);
$stmt_invoices->execute();
$result_invoices = $stmt_invoices->get_result();

// 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
                        JOIN lease_tenants lt ON l.id = lt.lease_id AND lt.is_primary = 1
                        WHERE lt.tenant_id = ? AND rp.payment_status = 'COMPLETED'
                        ORDER BY rp.payment_date DESC LIMIT 5";
$stmt_recent_payments = $conn->prepare($sql_recent_payments);
$stmt_recent_payments->bind_param("i", $tenant_id);
$stmt_recent_payments->execute();
$result_recent_payments = $stmt_recent_payments->get_result();
?>
<?php include 'layouts/main.php'; ?>

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

                    <?php if ($lease): ?>
                        <div class="row mb-3">
                            <div class="col-12">
                                <div class="card bg-soft-primary">
                                    <div class="card-body">
                                        <div class="row align-items-center">
                                            <div class="col-md-8">
                                                <h5 class="mb-2">Current Lease</h5>
                                                <p class="mb-1">
                                                    <strong><?php echo htmlspecialchars($lease['property_name']); ?></strong> - 
                                                    Unit <?php echo htmlspecialchars($lease['unit_number']); ?>
                                                </p>
                                                <p class="mb-0 text-muted">
                                                    <?php echo date('M d, Y', strtotime($lease['start_date'])); ?> to 
                                                    <?php echo date('M d, Y', strtotime($lease['end_date'])); ?>
                                                </p>
                                            </div>
                                            <div class="col-md-4 text-end">
                                                <a href="my_lease.php" class="btn btn-primary">
                                                    <i class="ri-file-text-line me-1"></i>View Lease Details
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <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">Outstanding</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-alert-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($outstanding_balance, 0); ?>
                                            </h4>
                                            <span class="badge bg-soft-danger text-danger mb-0">
                                                <?php echo $outstanding_count; ?> invoices
                                            </span>
                                        </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">This Month Paid</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-money-dollar-circle-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_paid, 0); ?>
                                            </h4>
                                            <span class="badge bg-soft-success text-success mb-0">
                                                <?php echo $monthly_payments; ?> payments
                                            </span>
                                        </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">Maintenance</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-tools-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">
                                                <?php echo number_format($pending_maintenance); ?>
                                            </h4>
                                            <a href="my_maintenance_requests.php" class="text-decoration-underline">View requests</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">Quick Actions</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-info rounded-circle fs-3">
                                                    <i class="ri-menu-line text-info"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <a href="pay_rent.php" class="btn btn-primary btn-sm">
                                                <i class="ri-money-dollar-circle-line me-1"></i>Pay Rent
                                            </a>
                                        </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 Invoices</h4>
                                    <a href="my_invoices.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>Invoice #</th>
                                                    <th>Property/Unit</th>
                                                    <th>Amount</th>
                                                    <th>Balance</th>
                                                    <th>Due Date</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_invoices && $result_invoices->num_rows > 0): ?>
                                                    <?php while($invoice = $result_invoices->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($invoice['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($invoice['unit_number']); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>KES <?php echo number_format($invoice['total_amount'], 2); ?></td>
                                                            <td>
                                                                <span class="fw-semibold <?php echo $invoice['balance'] > 0 ? 'text-danger' : 'text-success'; ?>">
                                                                    KES <?php echo number_format($invoice['balance'], 2); ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo date('M d, Y', strtotime($invoice['due_date'])); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-<?php echo $invoice['status'] == 'paid' ? 'success' : 'danger'; ?>">
                                                                    <?php echo ucfirst($invoice['status']); ?>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="6" class="text-center py-4">
                                                            <div class="text-muted">No invoices 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 Payments</h4>
                                    <a href="my_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>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>
                                                                <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="4" class="text-center py-4">
                                                            <div class="text-muted">No payments 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>
