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

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

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

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

// Get tenant details
$sql = "SELECT id, CONCAT(first_name, ' ', last_name) as full_name, email, phone 
        FROM users WHERE id = ? AND 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 filters
$status_filter = $_GET['status'] ?? '';
$type_filter = $_GET['type'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

// Build query
$sql = "SELECT i.*, p.name as property_name, p.location_area, u.unit_number
        FROM invoices i
        LEFT JOIN properties p ON i.property_id = p.id
        LEFT JOIN leases l ON i.lease_id = l.id
        LEFT JOIN units u ON l.unit_id = u.id
        WHERE i.tenant_id = ?";

$params = [$tenant_id];
$types = 'i';

if (!empty($status_filter)) {
    $sql .= " AND i.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

if (!empty($type_filter)) {
    $sql .= " AND i.type = ?";
    $params[] = $type_filter;
    $types .= 's';
}

if (!empty($date_from)) {
    $sql .= " AND i.due_date >= ?";
    $params[] = $date_from;
    $types .= 's';
}

if (!empty($date_to)) {
    $sql .= " AND i.due_date <= ?";
    $params[] = $date_to;
    $types .= 's';
}

$sql .= " ORDER BY i.due_date DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$invoices_result = $stmt->get_result();

// Get summary statistics
$stats_sql = "SELECT 
                COUNT(*) as total_invoices,
                SUM(total_amount) as total_amount,
                SUM(paid_amount) as paid_amount,
                SUM(balance) as total_balance,
                SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) as paid_count,
                SUM(CASE WHEN status = 'unpaid' THEN 1 ELSE 0 END) as unpaid_count,
                SUM(CASE WHEN status = 'overdue' THEN 1 ELSE 0 END) as overdue_count,
                SUM(CASE WHEN status = 'partial' THEN 1 ELSE 0 END) as partial_count
              FROM invoices WHERE tenant_id = ?";
$stats_stmt = $conn->prepare($stats_sql);
$stats_stmt->bind_param("i", $tenant_id);
$stats_stmt->execute();
$stats = $stats_stmt->get_result()->fetch_assoc();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Tenant Invoices')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .stats-card {
            border-left: 4px solid;
            transition: all 0.3s ease;
        }
        .stats-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 16px rgba(0,0,0,0.1);
        }
        .stats-card.primary { border-left-color: #405189; }
        .stats-card.success { border-left-color: #0ab39c; }
        .stats-card.warning { border-left-color: #f7b84b; }
        .stats-card.danger { border-left-color: #f06548; }
        
        .tenant-header {
            background: linear-gradient(135deg, #405189 0%, #556ee6 100%);
            color: white;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
        }
        .card {
            box-shadow: 0 0.75rem 1.5rem rgba(18,38,63,.03);
            border: 1px solid #e9ebec;
        }
        .table thead th {
            background-color: #f3f6f9;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 11px;
            letter-spacing: 0.5px;
            color: #405189;
            border-bottom: 2px solid #e9ebec;
        }
        .table tbody tr {
            transition: all 0.2s ease;
        }
        .table tbody tr:hover {
            background-color: #f8f9fa;
        }
        .badge-custom {
            padding: 6px 12px;
            font-weight: 500;
            font-size: 11px;
        }
        .invoice-number {
            font-family: 'Courier New', monospace;
            font-weight: 600;
            color: #405189;
        }
    </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' => 'Invoice Management', 
                        'title' => 'Tenant Invoices'
                    )); ?>

                    <!-- Tenant Info Header -->
                    <div class="tenant-header">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h4 class="mb-1">
                                    <i class="ri-user-3-line me-2"></i>
                                    <?php echo htmlspecialchars($tenant['full_name']); ?>
                                </h4>
                                <p class="mb-0 text-white-50">
                                    <i class="ri-mail-line me-1"></i><?php echo htmlspecialchars($tenant['email']); ?>
                                    <span class="mx-2">|</span>
                                    <i class="ri-phone-line me-1"></i><?php echo htmlspecialchars($tenant['phone']); ?>
                                </p>
                            </div>
                            <div>
                                <a href="tenant_details.php?id=<?php echo $tenant_id; ?>" class="btn btn-light">
                                    <i class="ri-arrow-left-line me-1"></i>Back to Profile
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="card stats-card primary mb-3">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-primary text-primary rounded-circle fs-3">
                                                    <i class="ri-file-list-3-line"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-muted mb-1">Total Invoices</p>
                                            <h4 class="mb-0"><?php echo $stats['total_invoices']; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card stats-card success mb-3">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-success text-success rounded-circle fs-3">
                                                    <i class="ri-check-double-line"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-muted mb-1">Total Paid</p>
                                            <h4 class="mb-0">KES <?php echo number_format($stats['paid_amount'], 2); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card stats-card warning mb-3">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-warning text-warning rounded-circle fs-3">
                                                    <i class="ri-time-line"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-muted mb-1">Outstanding</p>
                                            <h4 class="mb-0">KES <?php echo number_format($stats['total_balance'], 2); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card stats-card danger mb-3">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-danger text-danger rounded-circle fs-3">
                                                    <i class="ri-alert-line"></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-muted mb-1">Overdue</p>
                                            <h4 class="mb-0"><?php echo $stats['overdue_count']; ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <input type="hidden" name="tenant_id" value="<?php echo $tenant_id; ?>">
                                        <div class="col-md-3">
                                            <label class="form-label fw-semibold">
                                                <i class="ri-filter-3-line me-1"></i>Status
                                            </label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="unpaid" <?php echo $status_filter == 'unpaid' ? 'selected' : ''; ?>>Unpaid</option>
                                                <option value="partial" <?php echo $status_filter == 'partial' ? 'selected' : ''; ?>>Partial</option>
                                                <option value="paid" <?php echo $status_filter == 'paid' ? 'selected' : ''; ?>>Paid</option>
                                                <option value="overdue" <?php echo $status_filter == 'overdue' ? 'selected' : ''; ?>>Overdue</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label fw-semibold">
                                                <i class="ri-file-list-line me-1"></i>Type
                                            </label>
                                            <select class="form-select" name="type">
                                                <option value="">All Types</option>
                                                <option value="Rent" <?php echo $type_filter == 'Rent' ? 'selected' : ''; ?>>Rent</option>
                                                <option value="Water" <?php echo $type_filter == 'Water' ? 'selected' : ''; ?>>Water</option>
                                                <option value="Electricity" <?php echo $type_filter == 'Electricity' ? 'selected' : ''; ?>>Electricity</option>
                                                <option value="Service Charge" <?php echo $type_filter == 'Service Charge' ? 'selected' : ''; ?>>Service Charge</option>
                                                <option value="Penalty" <?php echo $type_filter == 'Penalty' ? 'selected' : ''; ?>>Penalty</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label fw-semibold">Date From</label>
                                            <input type="date" class="form-control" name="date_from" 
                                                   value="<?php echo htmlspecialchars($date_from); ?>">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label fw-semibold">Date To</label>
                                            <input type="date" class="form-control" name="date_to" 
                                                   value="<?php echo htmlspecialchars($date_to); ?>">
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label">&nbsp;</label>
                                            <button type="submit" class="btn btn-primary w-100">
                                                <i class="ri-search-line"></i>
                                            </button>
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label">&nbsp;</label>
                                            <a href="?tenant_id=<?php echo $tenant_id; ?>" class="btn btn-light w-100">
                                                <i class="ri-refresh-line"></i>
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Invoices Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex" style="background: linear-gradient(135deg, #405189 0%, #556ee6 100%); color: white;">
                                    <h4 class="card-title mb-0 flex-grow-1 text-white">
                                        <i class="ri-bill-line me-2"></i>Invoice History
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Invoice #</th>
                                                    <th>Property/Unit</th>
                                                    <th>Type</th>
                                                    <th>Amount</th>
                                                    <th>Paid</th>
                                                    <th>Balance</th>
                                                    <th>Due Date</th>
                                                    <th>Status</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($invoices_result->num_rows > 0): ?>
                                                    <?php while($invoice = $invoices_result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <span class="invoice-number">
                                                                    <?php echo htmlspecialchars($invoice['invoice_number']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <strong><?php echo htmlspecialchars($invoice['property_name'] ?? 'N/A'); ?></strong>
                                                                <?php if ($invoice['unit_number']): ?>
                                                                    <br><small class="text-muted">Unit <?php echo htmlspecialchars($invoice['unit_number']); ?></small>
                                                                <?php endif; ?>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info badge-custom">
                                                                    <?php echo htmlspecialchars($invoice['type']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <strong>KES <?php echo number_format($invoice['total_amount'], 2); ?></strong>
                                                            </td>
                                                            <td>
                                                                <span class="text-success">
                                                                    KES <?php echo number_format($invoice['paid_amount'], 2); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="text-danger">
                                                                    KES <?php echo number_format($invoice['balance'], 2); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php 
                                                                $due_date = strtotime($invoice['due_date']);
                                                                $today = strtotime('today');
                                                                $is_overdue = $due_date < $today && $invoice['status'] != 'paid';
                                                                ?>
                                                                <span class="<?php echo $is_overdue ? 'text-danger' : ''; ?>">
                                                                    <?php echo date('M d, Y', $due_date); ?>
                                                                </span>
                                                            </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; ?> badge-custom">
                                                                    <?php echo ucfirst($invoice['status']); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown-toggle" 
                                                                            type="button" data-bs-toggle="dropdown">
                                                                        <i class="ri-more-2-fill"></i>
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                                        <li>
                                                                            <a class="dropdown-item" href="invoice_details.php?id=<?php echo $invoice['id']; ?>">
                                                                                <i class="ri-eye-line align-bottom me-2 text-muted"></i>View Details
                                                                            </a>
                                                                        </li>
                                                                        <?php if ($invoice['status'] != 'paid'): ?>
                                                                        <li>
                                                                            <a class="dropdown-item" href="record_payment.php?invoice_id=<?php echo $invoice['id']; ?>">
                                                                                <i class="ri-money-dollar-circle-line align-bottom me-2 text-success"></i>Record Payment
                                                                            </a>
                                                                        </li>
                                                                        <?php endif; ?>
                                                                        <li>
                                                                            <a class="dropdown-item" href="download_invoice.php?id=<?php echo $invoice['id']; ?>">
                                                                                <i class="ri-download-line align-bottom me-2 text-info"></i>Download PDF
                                                                            </a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="9" class="text-center py-5">
                                                            <div class="text-muted">
                                                                <i class="ri-bill-line fs-48 text-primary"></i>
                                                                <p class="mt-3 fs-15">No invoices found</p>
                                                                <?php if (!empty($status_filter) || !empty($type_filter)): ?>
                                                                    <a href="?tenant_id=<?php echo $tenant_id; ?>" class="btn btn-light mt-2">
                                                                        <i class="ri-refresh-line me-1"></i>Clear Filters
                                                                    </a>
                                                                <?php endif; ?>
                                                            </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>