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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$role_name = $_SESSION['role_name'];


// Get filter parameters
$status_filter = $_GET['status'] ?? '';
$coverage_filter = $_GET['coverage'] ?? '';
$agent_filter = $_GET['agent'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$search = $_GET['search'] ?? '';

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$records_per_page = 25;
$offset = ($page - 1) * $records_per_page;

// Build WHERE clause
$where_conditions = ["1=1"];
$params = [];
$param_types = "";

if ($status_filter) {
    $where_conditions[] = "p.status = ?";
    $params[] = $status_filter;
    $param_types .= "s";
}

if ($coverage_filter) {
    $where_conditions[] = "p.coverage_type = ?";
    $params[] = $coverage_filter;
    $param_types .= "s";
}

if ($agent_filter) {
    $where_conditions[] = "p.agent_id = ?";
    $params[] = $agent_filter;
    $param_types .= "i";
}

if ($date_from) {
    $where_conditions[] = "p.inception_date >= ?";
    $params[] = $date_from;
    $param_types .= "s";
}

if ($date_to) {
    $where_conditions[] = "p.inception_date <= ?";
    $params[] = $date_to;
    $param_types .= "s";
}

if ($search) {
    $where_conditions[] = "(p.policy_number LIKE ? OR c.first_name LIKE ? OR c.last_name LIKE ? OR c.customer_number LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $param_types .= "ssss";
}

// For agents, show only their policies
if ($role_name == 'Insurance Agent') {
    $where_conditions[] = "p.agent_id = ?";
    $params[] = $user_id;
    $param_types .= "i";
}

$where_clause = implode(" AND ", $where_conditions);

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total 
              FROM policies p 
              LEFT JOIN customers c ON p.customer_id = c.customer_id 
              WHERE $where_clause";

$count_stmt = $conn->prepare($count_sql);
if ($param_types) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_records = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);

// Get policies
$sql = "SELECT p.*, 
               c.customer_number, c.first_name, c.last_name, c.phone_primary,
               ip.product_name, pc.category_name,
               ic.company_name,
               u.full_name as agent_name, u.agent_code,
               DATEDIFF(p.expiry_date, CURDATE()) as days_to_expiry
        FROM policies p
        LEFT JOIN customers c ON p.customer_id = c.customer_id
        LEFT JOIN insurance_products ip ON p.product_id = ip.product_id
        LEFT JOIN product_categories pc ON ip.category_id = pc.category_id
        LEFT JOIN insurance_companies ic ON p.company_id = ic.company_id
        LEFT JOIN users u ON p.agent_id = u.user_id
        WHERE $where_clause
        ORDER BY p.created_at DESC
        LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);
$params[] = $records_per_page;
$params[] = $offset;
$param_types .= "ii";

if ($param_types) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$policies_result = $stmt->get_result();

// Get summary statistics
$stats_sql = "SELECT 
                COUNT(*) as total_policies,
                SUM(CASE WHEN p.status = 'ACTIVE' THEN 1 ELSE 0 END) as active_policies,
                SUM(CASE WHEN p.status = 'PENDING' THEN 1 ELSE 0 END) as pending_policies,
                SUM(CASE WHEN p.status = 'LAPSED' THEN 1 ELSE 0 END) as lapsed_policies,
                SUM(CASE WHEN p.status = 'ACTIVE' THEN p.premium_amount ELSE 0 END) as total_premium,
                SUM(CASE WHEN p.status = 'ACTIVE' AND DATEDIFF(p.expiry_date, CURDATE()) <= 30 THEN 1 ELSE 0 END) as expiring_soon
              FROM policies p 
              WHERE " . ($role_name == 'Insurance Agent' ? "p.agent_id = $user_id" : "1=1");

$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

// Get agents for filter
$agents_sql = "SELECT user_id, full_name, agent_code FROM users WHERE agent_code IS NOT NULL AND status = 'ACTIVE' ORDER BY full_name";
$agents_result = $conn->query($agents_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Policies')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
    <style>
        .policy-card {
            transition: all 0.3s ease;
            border: 1px solid #e9ecef;
        }
        .policy-card:hover {
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
            transform: translateY(-2px);
        }
        .status-badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
        }
        .expiry-warning {
            background: linear-gradient(45deg, #ff6b6b, #feca57);
            color: white;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .filter-card {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Insurance Policies</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Policies</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="card border-0 shadow-sm">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-primary-subtle text-primary rounded-circle fs-3">
                                                <i class="ri-file-list-3-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">Total Policies</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['total_policies']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card border-0 shadow-sm">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-success-subtle text-success rounded-circle fs-3">
                                                <i class="ri-shield-check-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">Active Policies</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['active_policies']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card border-0 shadow-sm">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-warning-subtle text-warning rounded-circle fs-3">
                                                <i class="ri-time-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">Expiring Soon</p>
                                            <h4 class="mb-0"><?php echo number_format($stats['expiring_soon']); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="card border-0 shadow-sm">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-info-subtle text-info rounded-circle fs-3">
                                                <i class="ri-money-dollar-circle-line"></i>
                                            </span>
                                        </div>
                                        <div class="flex-grow-1 ms-3">
                                            <p class="text-uppercase fw-semibold fs-12 text-muted mb-1">Total Premium</p>
                                            <h4 class="mb-0">KSH <?php echo number_format($stats['total_premium'], 2); ?></h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card filter-card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <!-- Search -->
                                        <div class="col-md-3">
                                            <label class="form-label">Search</label>
                                            <input type="text" class="form-control" name="search" 
                                                   placeholder="Policy number, customer name..." 
                                                   value="<?php echo htmlspecialchars($search); ?>">
                                        </div>
                                        
                                        <!-- Status Filter -->
                                        <div class="col-md-2">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="">All Status</option>
                                                <option value="ACTIVE" <?php echo $status_filter == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                                <option value="PENDING" <?php echo $status_filter == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="LAPSED" <?php echo $status_filter == 'LAPSED' ? 'selected' : ''; ?>>Lapsed</option>
                                                <option value="CANCELLED" <?php echo $status_filter == 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                                <option value="EXPIRED" <?php echo $status_filter == 'EXPIRED' ? 'selected' : ''; ?>>Expired</option>
                                            </select>
                                        </div>
                                        
                                        <!-- Coverage Type -->
                                        <div class="col-md-2">
                                            <label class="form-label">Coverage</label>
                                            <select class="form-select" name="coverage">
                                                <option value="">All Coverage</option>
                                                <option value="HEALTH" <?php echo $coverage_filter == 'HEALTH' ? 'selected' : ''; ?>>Health</option>
                                                <option value="MOTOR" <?php echo $coverage_filter == 'MOTOR' ? 'selected' : ''; ?>>Motor</option>
                                                <option value="LIFE" <?php echo $coverage_filter == 'LIFE' ? 'selected' : ''; ?>>Life</option>
                                                <option value="PROPERTY" <?php echo $coverage_filter == 'PROPERTY' ? 'selected' : ''; ?>>Property</option>
                                                <option value="TRAVEL" <?php echo $coverage_filter == 'TRAVEL' ? 'selected' : ''; ?>>Travel</option>
                                            </select>
                                        </div>
                                        
                                        <!-- Agent Filter (only for admins) -->
                                        <?php if ($role_name != 'Insurance Agent'): ?>
                                        <div class="col-md-2">
                                            <label class="form-label">Agent</label>
                                            <select class="form-select" name="agent">
                                                <option value="">All Agents</option>
                                                <?php while ($agent = $agents_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $agent['user_id']; ?>" 
                                                            <?php echo $agent_filter == $agent['user_id'] ? 'selected' : ''; ?>>
                                                        <?php echo $agent['agent_code'] . ' - ' . $agent['full_name']; ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Date Range -->
                                        <div class="col-md-2">
                                            <label class="form-label">Date From</label>
                                            <input type="date" class="form-control" name="date_from" 
                                                   value="<?php echo $date_from; ?>">
                                        </div>
                                        
                                        <div class="col-md-2">
                                            <label class="form-label">Date To</label>
                                            <input type="date" class="form-control" name="date_to" 
                                                   value="<?php echo $date_to; ?>">
                                        </div>
                                        
                                        <!-- Filter Actions -->
                                        <div class="col-md-1">
                                            <label class="form-label">&nbsp;</label>
                                            <div class="d-grid">
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="ri-search-line"></i>
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-1">
                                            <label class="form-label">&nbsp;</label>
                                            <div class="d-grid">
                                                <a href="list_policies.php" class="btn btn-light">
                                                    <i class="ri-refresh-line"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Policies List -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-file-list-line me-2"></i>Policies List 
                                        <span class="badge bg-primary ms-2"><?php echo number_format($total_records); ?> total</span>
                                    </h5>
                                    
                                    <a href="issue_policy.php" class="btn btn-primary">
                                        <i class="ri-add-line me-1"></i> Issue New Policy
                                    </a>
                                   
                                </div>
                                <div class="card-body p-0">
                                    <?php if ($policies_result->num_rows > 0): ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover align-middle mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Policy Details</th>
                                                    <th>Customer</th>
                                                    <th>Product</th>
                                                    <th>Premium</th>
                                                    <th>Agent</th>
                                                    <th>Dates</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($policy = $policies_result->fetch_assoc()): 
                                                    $status_class = match($policy['status']) {
                                                        'ACTIVE' => 'success',
                                                        'PENDING' => 'warning',
                                                        'LAPSED' => 'danger',
                                                        'CANCELLED' => 'secondary',
                                                        'EXPIRED' => 'dark',
                                                        default => 'info'
                                                    };
                                                    
                                                    $expiry_class = '';
                                                    if ($policy['days_to_expiry'] <= 0) {
                                                        $expiry_class = 'text-danger';
                                                    } elseif ($policy['days_to_expiry'] <= 30) {
                                                        $expiry_class = 'text-warning';
                                                    }
                                                ?>
                                                <tr>
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-1">
                                                                <a href="view_policy.php?id=<?php echo $policy['policy_id']; ?>" 
                                                                   class="text-primary text-decoration-none">
                                                                    <?php echo $policy['policy_number']; ?>
                                                                </a>
                                                            </h6>
                                                            <p class="text-muted mb-0 small">
                                                                <?php echo ucfirst(strtolower($policy['policy_type'])); ?> Policy
                                                            </p>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="avatar-xs me-2">
                                                                <span class="avatar-title bg-soft-primary text-primary rounded-circle">
                                                                    <?php echo strtoupper(substr($policy['first_name'], 0, 1)); ?>
                                                                </span>
                                                            </div>
                                                            <div>
                                                                <h6 class="mb-0"><?php echo $policy['first_name'] . ' ' . $policy['last_name']; ?></h6>
                                                                <p class="text-muted mb-0 small"><?php echo $policy['customer_number']; ?></p>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-1"><?php echo $policy['product_name']; ?></h6>
                                                            <span class="badge bg-soft-info text-info">
                                                                <?php echo $policy['category_name']; ?>
                                                            </span>
                                                            <p class="text-muted mb-0 small"><?php echo $policy['company_name']; ?></p>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-1">KSH <?php echo number_format($policy['premium_amount'], 2); ?></h6>
                                                            <p class="text-muted mb-0 small">
                                                                <?php echo ucfirst(strtolower($policy['premium_frequency'])); ?>
                                                            </p>
                                                            <p class="text-muted mb-0 small">
                                                                Sum: KSH <?php echo number_format($policy['sum_assured'], 2); ?>
                                                            </p>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-0"><?php echo $policy['agent_name']; ?></h6>
                                                            <p class="text-muted mb-0 small"><?php echo $policy['agent_code']; ?></p>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <p class="mb-1 small">
                                                                <strong>Start:</strong> <?php echo date('M j, Y', strtotime($policy['inception_date'])); ?>
                                                            </p>
                                                            <p class="mb-0 small <?php echo $expiry_class; ?>">
                                                                <strong>Expires:</strong> <?php echo date('M j, Y', strtotime($policy['expiry_date'])); ?>
                                                                <?php if ($policy['days_to_expiry'] <= 30 && $policy['days_to_expiry'] > 0): ?>
                                                                    <br><span class="expiry-warning">
                                                                        <?php echo $policy['days_to_expiry']; ?> days left
                                                                    </span>
                                                                <?php elseif ($policy['days_to_expiry'] <= 0): ?>
                                                                    <br><span class="badge bg-danger">Expired</span>
                                                                <?php endif; ?>
                                                            </p>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-<?php echo $status_class; ?> status-badge">
                                                            <?php echo ucfirst(strtolower($policy['status'])); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="dropdown">
                                                            <button class="btn btn-light btn-sm dropdown-toggle" type="button" 
                                                                    data-bs-toggle="dropdown" aria-expanded="false">
                                                                <i class="ri-more-2-fill"></i>
                                                            </button>
                                                            <ul class="dropdown-menu">
                                                                <li>
                                                                    <a class="dropdown-item" href="view_policy.php?id=<?php echo $policy['policy_id']; ?>">
                                                                        <i class="ri-eye-line me-2"></i>View Details
                                                                    </a>
                                                                </li>
                                                                
                                                                <li>
                                                                    <a class="dropdown-item" href="edit_policy.php?id=<?php echo $policy['policy_id']; ?>">
                                                                        <i class="ri-edit-line me-2"></i>Edit Policy
                                                                    </a>
                                                                </li>
                                                               
                                                                <li>
                                                                    <a class="dropdown-item" href="endorsements.php?policy_id=<?php echo $policy['policy_id']; ?>">
                                                                        <i class="ri-file-edit-line me-2"></i>Endorsement
                                                                    </a>
                                                                </li>
                                                                
                                                                <li>
                                                                    <a class="dropdown-item" href="renew_policy.php?id=<?php echo $policy['policy_id']; ?>">
                                                                        <i class="ri-refresh-line me-2"></i>Renew Policy
                                                                    </a>
                                                                </li>
                                                               
                                                                <li><hr class="dropdown-divider"></li>
                                                                <li>
                                                                    <a class="dropdown-item" href="policy_documents.php?id=<?php echo $policy['policy_id']; ?>">
                                                                        <i class="ri-file-text-line me-2"></i>Documents
                                                                    </a>
                                                                </li>
                                                                <li>
                                                                    <a class="dropdown-item" href="claims/list_claims.php?policy_id=<?php echo $policy['policy_id']; ?>">
                                                                        <i class="ri-hand-heart-line me-2"></i>Claims
                                                                    </a>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <!-- Pagination -->
                                    <?php if ($total_pages > 1): ?>
                                    <div class="card-footer">
                                        <div class="row align-items-center">
                                            <div class="col-sm-6">
                                                <div class="text-muted">
                                                    Showing <?php echo ($offset + 1); ?> to 
                                                    <?php echo min($offset + $records_per_page, $total_records); ?> 
                                                    of <?php echo $total_records; ?> entries
                                                </div>
                                            </div>
                                            <div class="col-sm-6">
                                                <nav aria-label="Page navigation">
                                                    <ul class="pagination justify-content-end mb-0">
                                                        <?php if ($page > 1): ?>
                                                        <li class="page-item">
                                                            <a class="page-link" href="?page=<?php echo ($page-1); ?>&<?php echo http_build_query($_GET); ?>">
                                                                <i class="ri-arrow-left-line"></i>
                                                            </a>
                                                        </li>
                                                        <?php endif; ?>
                                                        
                                                        <?php for ($i = max(1, $page-2); $i <= min($total_pages, $page+2); $i++): ?>
                                                        <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                                            <a class="page-link" href="?page=<?php echo $i; ?>&<?php echo http_build_query($_GET); ?>">
                                                                <?php echo $i; ?>
                                                            </a>
                                                        </li>
                                                        <?php endfor; ?>
                                                        
                                                        <?php if ($page < $total_pages): ?>
                                                        <li class="page-item">
                                                            <a class="page-link" href="?page=<?php echo ($page+1); ?>&<?php echo http_build_query($_GET); ?>">
                                                                <i class="ri-arrow-right-line"></i>
                                                            </a>
                                                        </li>
                                                        <?php endif; ?>
                                                    </ul>
                                                </nav>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php else: ?>
                                    <div class="text-center py-5">
                                        <div class="avatar-lg mx-auto mb-4">
                                            <div class="avatar-title bg-light text-muted rounded-circle">
                                                <i class="ri-file-list-line fs-1"></i>
                                            </div>
                                        </div>
                                        <h5>No policies found</h5>
                                        <p class="text-muted">Try adjusting your search filters or 
                                            <a href="issue_policy.php">issue a new policy</a>.
                                        </p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <script>
        $(document).ready(function() {
            // Initialize date pickers
            flatpickr("input[name='date_from'], input[name='date_to']", {
                dateFormat: "Y-m-d"
            });

            // Auto-submit form when filters change
            $('select[name="status"], select[name="coverage"], select[name="agent"]').change(function() {
                $(this).closest('form').submit();
            });
        });
    </script>
</body>
</html>