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

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

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

$user_id = $_SESSION['user_id'];

// Total Properties Managed
$sql_properties = "SELECT COUNT(*) as total FROM properties";
$result_properties = $conn->query($sql_properties);
$total_properties = $result_properties->fetch_assoc()['total'] ?? 0;

// Active Tenants
$sql_tenants = "SELECT COUNT(DISTINCT t.tenant_id) as total
                FROM tenants t
                JOIN lease_tenants lt ON t.tenant_id = lt.tenant_id
                JOIN leases l ON lt.lease_id = l.lease_id
                WHERE l.lease_status = 'ACTIVE'";
$result_tenants = $conn->query($sql_tenants);
$active_tenants = $result_tenants->fetch_assoc()['total'] ?? 0;

// Vacant Units
$sql_vacant = "SELECT COUNT(*) as total FROM units WHERE status = 'vacant'";
$result_vacant = $conn->query($sql_vacant);
$vacant_units = $result_vacant->fetch_assoc()['total'] ?? 0;

// Leases Expiring Soon (Next 30 days)
$sql_expiring = "SELECT COUNT(*) as total FROM leases 
                 WHERE lease_status = 'ACTIVE' 
                 AND end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)";
$result_expiring = $conn->query($sql_expiring);
$expiring_leases = $result_expiring->fetch_assoc()['total'] ?? 0;

// Pending Maintenance Requests
$sql_maintenance = "SELECT COUNT(*) as total FROM maintenance_requests 
                    WHERE status IN ('Open', 'NEW', 'Assigned')";
$result_maintenance = $conn->query($sql_maintenance);
$pending_maintenance = $result_maintenance->fetch_assoc()['total'] ?? 0;

// Recent Lease Renewals Needed
$sql_renewals = "SELECT l.*, u.unit_number, p.name as property_name,
                        t.first_name, t.last_name
                 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
                 JOIN tenants t ON lt.tenant_id = t.tenant_id
                 WHERE l.lease_status = 'ACTIVE'
                 AND l.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
                 ORDER BY l.end_date ASC LIMIT 5";
$result_renewals = $conn->query($sql_renewals);

// Recent Maintenance Requests
$sql_recent_maint = "SELECT mr.*, p.name as property_name, u.unit_number
                     FROM maintenance_requests mr
                     LEFT JOIN properties p ON mr.property_id = p.id
                     LEFT JOIN units u ON mr.unit_id = u.id
                     WHERE mr.status IN ('Open', 'NEW', 'Assigned')
                     ORDER BY mr.created_at DESC LIMIT 5";
$result_recent_maint = $conn->query($sql_recent_maint);
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Property Agent 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' => 'Property Agent 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">Properties</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-primary rounded-circle fs-3">
                                                    <i class="ri-building-line text-primary"></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($total_properties); ?>
                                            </h4>
                                            <a href="list_properties.php" class="text-decoration-underline">View all</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">Active Tenants</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-user-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">
                                                <?php echo number_format($active_tenants); ?>
                                            </h4>
                                            <a href="list_tenants.php" class="text-decoration-underline">View all</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">Vacant Units</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-home-4-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($vacant_units); ?>
                                            </h4>
                                            <a href="vacant_units.php" class="text-decoration-underline">View all</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">Expiring Leases</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-calendar-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">
                                                <?php echo number_format($expiring_leases); ?>
                                            </h4>
                                            <a href="lease_renewals.php" class="text-decoration-underline">View renewals</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">Leases Expiring Soon</h4>
                                    <a href="lease_renewals.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>Tenant</th>
                                                    <th>Property/Unit</th>
                                                    <th>End Date</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_renewals && $result_renewals->num_rows > 0): ?>
                                                    <?php while($lease = $result_renewals->fetch_assoc()): 
                                                        $days_left = round((strtotime($lease['end_date']) - strtotime('today')) / (60 * 60 * 24));
                                                    ?>
                                                        <tr>
                                                            <td>
                                                                <h5 class="fs-14 mb-0">
                                                                    <?php echo htmlspecialchars($lease['first_name'] . ' ' . $lease['last_name']); ?>
                                                                </h5>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($lease['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($lease['unit_number']); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="<?php echo $days_left <= 15 ? 'text-danger' : 'text-warning'; ?>">
                                                                    <?php echo date('M d, Y', strtotime($lease['end_date'])); ?>
                                                                </span>
                                                                <br><small class="text-muted"><?php echo $days_left; ?> days left</small>
                                                            </td>
                                                            <td>
                                                                <a href="create_lease.php?renew=<?php echo $lease['lease_id']; ?>" 
                                                                   class="btn btn-primary btn-sm">
                                                                    <i class="ri-refresh-line me-1"></i>Renew
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="4" class="text-center py-4">
                                                            <div class="text-muted">No leases expiring soon</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">Pending Maintenance</h4>
                                    <a href="list_maintenance.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>Ticket #</th>
                                                    <th>Property/Unit</th>
                                                    <th>Priority</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_recent_maint && $result_recent_maint->num_rows > 0): ?>
                                                    <?php while($maint = $result_recent_maint->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($maint['ticket_number'] ?? $maint['request_code']); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($maint['property_name'] ?? 'N/A'); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($maint['unit_number'] ?? 'N/A'); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-warning"><?php echo htmlspecialchars($maint['priority']); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-primary"><?php echo htmlspecialchars($maint['status']); ?></span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="4" class="text-center py-4">
                                                            <div class="text-muted">No pending maintenance</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>
