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

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

$tenant_id = $_GET['id'] ?? null;

if (!$tenant_id) {
    header('Location: list_tenants.php');
    exit();
}

// Get tenant details
$sql = "SELECT u.*, tk.* 
        FROM users u 
        LEFT JOIN tenant_kyc tk ON u.id = tk.user_id 
        WHERE u.id = ? AND u.role_id = 4";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $tenant_id);
$stmt->execute();
$result = $stmt->get_result();
$tenant = $result->fetch_assoc();

if (!$tenant) {
    $_SESSION['error_message'] = "Tenant not found!";
    header('Location: list_tenants.php');
    exit();
}

// Get active leases
$leases_sql = "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
               WHERE l.tenant_id = ?
               ORDER BY l.start_date DESC";
$leases_stmt = $conn->prepare($leases_sql);
$leases_stmt->bind_param("i", $tenant_id);
$leases_stmt->execute();
$leases_result = $leases_stmt->get_result();

// Get payment statistics
$payment_stats_sql = "SELECT 
                        COUNT(DISTINCT i.id) as total_invoices,
                        SUM(CASE WHEN i.status = 'paid' THEN 1 ELSE 0 END) as paid_invoices,
                        SUM(CASE WHEN i.status = 'overdue' THEN 1 ELSE 0 END) as overdue_invoices,
                        SUM(i.total_amount) as total_billed,
                        SUM(i.paid_amount) as total_paid,
                        SUM(i.balance) as total_balance
                      FROM invoices i
                      WHERE i.tenant_id = ?";
$payment_stmt = $conn->prepare($payment_stats_sql);
$payment_stmt->bind_param("i", $tenant_id);
$payment_stmt->execute();
$payment_stats = $payment_stmt->get_result()->fetch_assoc();

// Get recent invoices
$invoices_sql = "SELECT i.*, p.name as property_name
                 FROM invoices i
                 LEFT JOIN properties p ON i.property_id = p.id
                 WHERE i.tenant_id = ?
                 ORDER BY i.due_date DESC
                 LIMIT 5";
$invoices_stmt = $conn->prepare($invoices_sql);
$invoices_stmt->bind_param("i", $tenant_id);
$invoices_stmt->execute();
$invoices_result = $invoices_stmt->get_result();

// Get maintenance requests
$maintenance_sql = "SELECT m.*, p.name as property_name, u.unit_number
                    FROM maintenance_requests m
                    JOIN properties p ON m.property_id = p.id
                    LEFT JOIN units u ON m.unit_id = u.id
                    WHERE m.requester_id = ?
                    ORDER BY m.created_at DESC
                    LIMIT 5";
$maintenance_stmt = $conn->prepare($maintenance_sql);
$maintenance_stmt->bind_param("i", $tenant_id);
$maintenance_stmt->execute();
$maintenance_result = $maintenance_stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Tenant Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .profile-header {
            background: linear-gradient(135deg, #405189 0%, #556ee6 100%);
            color: white;
            padding: 2rem;
            border-radius: 8px 8px 0 0;
        }
        .profile-avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: white;
            color: #405189;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 36px;
            font-weight: 700;
            border: 4px solid rgba(255,255,255,0.3);
        }
        .info-card {
            border-left: 4px solid #405189;
            transition: all 0.3s ease;
        }
        .info-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        .stat-box {
            text-align: center;
            padding: 1.5rem;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        .stat-box h3 {
            color: #405189;
            margin: 0;
            font-size: 28px;
            font-weight: 700;
        }
        .stat-box p {
            margin: 0.5rem 0 0 0;
            color: #878a99;
            font-size: 13px;
        }
        .section-title {
            border-left: 4px solid #405189;
            padding-left: 12px;
            margin: 2rem 0 1rem 0;
        }
        .section-title h5 {
            margin: 0;
            color: #405189;
            font-weight: 600;
        }
        .detail-row {
            padding: 0.75rem 0;
            border-bottom: 1px solid #e9ebec;
        }
        .detail-row:last-child {
            border-bottom: none;
        }
        .detail-label {
            font-weight: 600;
            color: #878a99;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .detail-value {
            color: #212529;
            font-size: 15px;
        }
        .action-btn {
            margin: 0 0.25rem;
            transition: all 0.2s ease;
        }
        .action-btn:hover {
            transform: translateY(-2px);
        }
    </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' => 'Tenant Management', 'title' => 'Tenant Details')); ?>

                    <!-- Profile Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card mb-3">
                                <div class="profile-header">
                                    <div class="d-flex align-items-center">
                                        <div class="profile-avatar me-4">
                                            <?php echo strtoupper(substr($tenant['first_name'], 0, 1) . substr($tenant['last_name'], 0, 1)); ?>
                                        </div>
                                        <div class="flex-grow-1">
                                            <h3 class="mb-1">
                                                <?php echo htmlspecialchars($tenant['first_name'] . ' ' . ($tenant['middle_name'] ? $tenant['middle_name'] . ' ' : '') . $tenant['last_name']); ?>
                                            </h3>
                                            <p class="mb-2 text-white-50">
                                                <i class="ri-mail-line me-2"></i><?php echo htmlspecialchars($tenant['email']); ?>
                                                <span class="mx-2">|</span>
                                                <i class="ri-phone-line me-2"></i><?php echo htmlspecialchars($tenant['phone']); ?>
                                            </p>
                                            <div class="d-flex gap-2 mt-3">
                                                <?php
                                                $status_colors = [
                                                    'active' => 'success',
                                                    'inactive' => 'warning',
                                                    'banned' => 'danger'
                                                ];
                                                $status_color = $status_colors[$tenant['status']] ?? 'secondary';
                                                ?>
                                                <span class="badge bg-<?php echo $status_color; ?>">
                                                    <?php echo ucfirst($tenant['status']); ?>
                                                </span>
                                                <?php if ($tenant['is_verified']): ?>
                                                <span class="badge bg-info">
                                                    <i class="ri-verified-badge-line me-1"></i>Verified
                                                </span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <div class="text-end">
                                            <a href="add_tenant.php?id=<?php echo $tenant_id; ?>" class="btn btn-light action-btn">
                                                <i class="ri-pencil-line me-1"></i>Edit
                                            </a>
                                            <a href="create_lease.php?tenant_id=<?php echo $tenant_id; ?>" class="btn btn-success action-btn">
                                                <i class="ri-file-add-line me-1"></i>Create Lease
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Stats Row -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="stat-box">
                                <h3><?php echo $leases_result->num_rows; ?></h3>
                                <p><i class="ri-file-list-line me-1"></i>Total Leases</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-box">
                                <h3>KES <?php echo number_format($payment_stats['total_paid'] ?? 0, 2); ?></h3>
                                <p><i class="ri-money-dollar-circle-line me-1"></i>Total Paid</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-box">
                                <h3>KES <?php echo number_format($payment_stats['total_balance'] ?? 0, 2); ?></h3>
                                <p><i class="ri-wallet-line me-1"></i>Outstanding Balance</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stat-box">
                                <h3><?php echo $payment_stats['overdue_invoices'] ?? 0; ?></h3>
                                <p><i class="ri-alert-line me-1"></i>Overdue Invoices</p>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-lg-4">
                            <!-- Personal Information -->
                            <div class="card info-card mb-3">
                                <div class="card-header bg-soft-primary">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-user-line me-2"></i>Personal Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="detail-row">
                                        <div class="detail-label">Full Name</div>
                                        <div class="detail-value">
                                            <?php echo htmlspecialchars($tenant['first_name'] . ' ' . ($tenant['middle_name'] ? $tenant['middle_name'] . ' ' : '') . $tenant['last_name']); ?>
                                        </div>
                                    </div>
                                    <div class="detail-row">
                                        <div class="detail-label">Gender</div>
                                        <div class="detail-value"><?php echo htmlspecialchars($tenant['gender'] ?? 'N/A'); ?></div>
                                    </div>
                                    <div class="detail-row">
                                        <div class="detail-label">Date of Birth</div>
                                        <div class="detail-value">
                                            <?php echo $tenant['dob'] ? date('M d, Y', strtotime($tenant['dob'])) : 'N/A'; ?>
                                        </div>
                                    </div>
                                    <div class="detail-row">
                                        <div class="detail-label">Nationality</div>
                                        <div class="detail-value"><?php echo htmlspecialchars($tenant['nationality'] ?? 'N/A'); ?></div>
                                    </div>
                                    <div class="detail-row">
                                        <div class="detail-label"><?php echo $tenant['id_type']; ?></div>
                                        <div class="detail-value"><?php echo htmlspecialchars($tenant['id_number'] ?? 'N/A'); ?></div>
                                    </div>
                                    <div class="detail-row">
                                        <div class="detail-label">KRA PIN</div>
                                        <div class="detail-value"><?php echo htmlspecialchars($tenant['kra_pin'] ?? 'N/A'); ?></div>
                                    </div>
                                </div>
                            </div>

                            <!-- Contact Information -->
                            <div class="card info-card mb-3">
                                <div class="card-header bg-soft-info">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-phone-line me-2"></i>Contact Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="detail-row">
                                        <div class="detail-label">Email</div>
                                        <div class="detail-value">
                                            <a href="mailto:<?php echo $tenant['email']; ?>">
                                                <?php echo htmlspecialchars($tenant['email']); ?>
                                            </a>
                                        </div>
                                    </div>
                                    <div class="detail-row">
                                        <div class="detail-label">Primary Phone</div>
                                        <div class="detail-value">
                                            <a href="tel:<?php echo $tenant['phone']; ?>">
                                                <?php echo htmlspecialchars($tenant['phone']); ?>
                                            </a>
                                        </div>
                                    </div>
                                    <?php if (!empty($tenant['phone_secondary'])): ?>
                                    <div class="detail-row">
                                        <div class="detail-label">Secondary Phone</div>
                                        <div class="detail-value">
                                            <a href="tel:<?php echo $tenant['phone_secondary']; ?>">
                                                <?php echo htmlspecialchars($tenant['phone_secondary']); ?>
                                            </a>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    <div class="detail-row">
                                        <div class="detail-label">Address</div>
                                        <div class="detail-value">
                                            <?php echo htmlspecialchars($tenant['address_postal'] ?? 'N/A'); ?>
                                            <?php if ($tenant['city']): ?>
                                                <br><?php echo htmlspecialchars($tenant['city']); ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Employment Information -->
                            <div class="card info-card mb-3">
                                <div class="card-header bg-soft-success">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-briefcase-line me-2"></i>Employment
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="detail-row">
                                        <div class="detail-label">Occupation</div>
                                        <div class="detail-value"><?php echo htmlspecialchars($tenant['occupation'] ?? 'N/A'); ?></div>
                                    </div>
                                    <div class="detail-row">
                                        <div class="detail-label">Employer</div>
                                        <div class="detail-value"><?php echo htmlspecialchars($tenant['employer_name'] ?? 'N/A'); ?></div>
                                    </div>
                                    <?php if (!empty($tenant['employer_phone'])): ?>
                                    <div class="detail-row">
                                        <div class="detail-label">Employer Phone</div>
                                        <div class="detail-value"><?php echo htmlspecialchars($tenant['employer_phone']); ?></div>
                                    </div>
                                    <?php endif; ?>
                                    <div class="detail-row">
                                        <div class="detail-label">Monthly Income</div>
                                        <div class="detail-value">
                                            <?php echo $tenant['monthly_income_range'] ? 'KES ' . htmlspecialchars($tenant['monthly_income_range']) : 'N/A'; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Emergency Contact -->
                            <div class="card info-card">
                                <div class="card-header bg-soft-warning">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-user-heart-line me-2"></i>Emergency Contact
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="detail-row">
                                        <div class="detail-label">Name</div>
                                        <div class="detail-value"><?php echo htmlspecialchars($tenant['nok_name'] ?? 'N/A'); ?></div>
                                    </div>
                                    <div class="detail-row">
                                        <div class="detail-label">Relationship</div>
                                        <div class="detail-value"><?php echo htmlspecialchars($tenant['nok_relation'] ?? 'N/A'); ?></div>
                                    </div>
                                    <div class="detail-row">
                                        <div class="detail-label">Phone</div>
                                        <div class="detail-value">
                                            <?php if (!empty($tenant['nok_phone'])): ?>
                                                <a href="tel:<?php echo $tenant['nok_phone']; ?>">
                                                    <?php echo htmlspecialchars($tenant['nok_phone']); ?>
                                                </a>
                                            <?php else: ?>
                                                N/A
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column -->
                        <div class="col-lg-8">
                            <!-- Active Leases -->
                            <div class="card mb-3">
                                <div class="card-header d-flex align-items-center" style="background: linear-gradient(135deg, #405189 0%, #556ee6 100%); color: white;">
                                    <h5 class="card-title mb-0 flex-grow-1 text-white">
                                        <i class="ri-file-list-3-line me-2"></i>Leases
                                    </h5>
                                    <a href="create_lease.php?tenant_id=<?php echo $tenant_id; ?>" class="btn btn-light btn-sm">
                                        <i class="ri-add-line me-1"></i>New Lease
                                    </a>
                                </div>
                                <div class="card-body">
                                    <?php if ($leases_result->num_rows > 0): ?>
                                        <div class="table-responsive">
                                            <table class="table table-hover mb-0">
                                                <thead>
                                                    <tr>
                                                        <th>Property</th>
                                                        <th>Unit</th>
                                                        <th>Period</th>
                                                        <th>Rent</th>
                                                        <th>Status</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while($lease = $leases_result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <strong><?php echo htmlspecialchars($lease['property_name']); ?></strong>
                                                                <br><small class="text-muted"><?php echo htmlspecialchars($lease['location_area']); ?></small>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($lease['unit_number']); ?></td>
                                                            <td>
                                                                <small>
                                                                    <?php echo date('M d, Y', strtotime($lease['start_date'])); ?><br>
                                                                    to <?php echo date('M d, Y', strtotime($lease['end_date'])); ?>
                                                                </small>
                                                            </td>
                                                            <td>
                                                                <strong>KES <?php echo number_format($lease['rent_amount'], 2); ?></strong>
                                                                <br><small class="text-muted"><?php echo ucfirst($lease['payment_frequency']); ?></small>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $status_badges = [
                                                                    'active' => 'success',
                                                                    'terminated' => 'danger',
                                                                    'expired' => 'warning',
                                                                    'eviction_pending' => 'danger'
                                                                ];
                                                                $badge = $status_badges[$lease['status']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $badge; ?> text-<?php echo $badge; ?>">
                                                                    <?php echo ucfirst(str_replace('_', ' ', $lease['status'])); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <a href="lease_details.php?id=<?php echo $lease['id']; ?>" class="btn btn-sm btn-soft-primary">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center py-4 text-muted">
                                            <i class="ri-file-list-line fs-48"></i>
                                            <p class="mt-2">No leases found</p>
                                            <a href="create_lease.php?tenant_id=<?php echo $tenant_id; ?>" class="btn btn-primary btn-sm">
                                                <i class="ri-add-line me-1"></i>Create First Lease
                                            </a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Recent Invoices -->
                            <div class="card mb-3">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">
                                        <i class="ri-bill-line me-2"></i>Recent Invoices
                                    </h5>
                                    <a href="tenant_invoices.php?tenant_id=<?php echo $tenant_id; ?>" class="btn btn-soft-primary btn-sm">
                                        View All
                                    </a>
                                </div>
                                <div class="card-body">
                                    <?php if ($invoices_result->num_rows > 0): ?>
                                        <div class="table-responsive">
                                            <table class="table table-hover mb-0">
                                                <thead>
                                                    <tr>
                                                        <th>Invoice #</th>
                                                        <th>Type</th>
                                                        <th>Amount</th>
                                                        <th>Due Date</th>
                                                        <th>Status</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while($invoice = $invoices_result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>
                                                            <td><?php echo htmlspecialchars($invoice['type']); ?></td>
                                                            <td><strong>KES <?php echo number_format($invoice['total_amount'], 2); ?></strong></td>
                                                            <td><?php echo date('M d, Y', strtotime($invoice['due_date'])); ?></td>
                                                            <td>
                                                                <?php
                                                                $status_badges = [
                                                                    'paid' => 'success',
                                                                    'partial' => 'info',
                                                                    'unpaid' => 'warning',
                                                                    'overdue' => 'danger',
                                                                    'void' => 'secondary'
                                                                ];
                                                                $badge = $status_badges[$invoice['status']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $badge; ?> text-<?php echo $badge; ?>">
                                                                    <?php echo ucfirst($invoice['status']); ?>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center py-4 text-muted">
                                            <i class="ri-bill-line fs-48"></i>
                                            <p class="mt-2">No invoices found</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Maintenance Requests -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-tools-line me-2"></i>Recent Maintenance Requests
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($maintenance_result->num_rows > 0): ?>
                                        <div class="table-responsive">
                                            <table class="table table-hover mb-0">
                                                <thead>
                                                    <tr>
                                                        <th>Ticket #</th>
                                                        <th>Subject</th>
                                                        <th>Property/Unit</th>
                                                        <th>Priority</th>
                                                        <th>Status</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while($maintenance = $maintenance_result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($maintenance['ticket_number'] ?? 'N/A'); ?></td>
                                                            <td><?php echo htmlspecialchars($maintenance['subject']); ?></td>
                                                            <td>
                                                                <small>
                                                                    <?php echo htmlspecialchars($maintenance['property_name']); ?>
                                                                    <?php if ($maintenance['unit_number']): ?>
                                                                        - Unit <?php echo htmlspecialchars($maintenance['unit_number']); ?>
                                                                    <?php endif; ?>
                                                                </small>
                                                            </td>
                                                            <td>
                                                                <?php
                                                                $priority_badges = [
                                                                    'Low' => 'info',
                                                                    'Medium' => 'warning',
                                                                    'High' => 'danger',
                                                                    'Emergency' => 'danger'
                                                                ];
                                                                $badge = $priority_badges[$maintenance['priority']] ?? 'secondary';
                                                                ?>
                                                                <span class="badge bg-soft-<?php echo $badge; ?> text-<?php echo $badge; ?>">
                                                                    <?php echo $maintenance['priority']; ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo $maintenance['status']; ?>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center py-4 text-muted">
                                            <i class="ri-tools-line fs-48"></i>
                                            <p class="mt-2">No maintenance requests</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

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

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