<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';
require_once('fpdf/fpdf.php');

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

// Fetch corporates for dropdown
$sql_corporates = "SELECT corp_id, corporate FROM corporate WHERE cancelled = 0 ORDER BY corporate";
$result_corporates = $conn->query($sql_corporates);
$corporates = [];
if ($result_corporates) {
    while ($row = $result_corporates->fetch_assoc()) {
        $corporates[] = $row;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Generate Policy Document')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</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' => 'Documents', 'title' => 'Policy Generator')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Generate Policy Document</h4>
                                </div>
                                
                                <div class="card-body">
                                    <!-- Corporate Selection -->
                                    <div class="row mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label">Select Corporate</label>
                                            <select class="form-select" id="corporateSelect">
                                                <option value="">Choose Corporate...</option>
                                                <?php foreach ($corporates as $corporate): ?>
                                                    <option value="<?php echo $corporate['corp_id']; ?>">
                                                        <?php echo htmlspecialchars($corporate['corporate']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>

                                    <!-- Members Table -->
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Member No</th>
                                                    <th>Name</th>
                                                    <th>Family No</th>
                                                    <th>Relationship</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody id="membersTable">
                                                <!-- Members will be loaded here -->
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const corporateSelect = document.getElementById('corporateSelect');

        // Handle corporate selection
        corporateSelect.addEventListener('change', function() {
            const corpId = this.value;
            if (!corpId) return;

            // Fetch members for selected corporate
            fetch('get_corporate_members.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `corp_id=${encodeURIComponent(corpId)}`
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    throw new Error(data.error || 'Failed to fetch members');
                }
                displayMembers(data.members);
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
        });

        // Display members in table
        function displayMembers(members) {
            const tbody = document.getElementById('membersTable');
            tbody.innerHTML = '';

            members.forEach(member => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${member.member_no}</td>
                    <td>${member.surname} ${member.first_name}</td>
                    <td>${member.family_no}</td>
                    <td>${getRelationshipText(member.relation_to_principal)}</td>
                    <td>
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-primary" 
                                    onclick="generateMemberPolicy('${member.member_no}')">
                                Member Policy
                            </button>
                            <button type="button" class="btn btn-sm btn-info" 
                                    onclick="generateFamilyPolicy('${member.family_no}')">
                                Family Policy
                            </button>
                        </div>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }

        // Helper function to convert relationship codes to text
        function getRelationshipText(relation) {
            const relationships = {
                1: 'Principal',
                2: 'Spouse',
                3: 'Child',
                4: 'Parent'
            };
            return relationships[relation] || 'Unknown';
        }

        // Add to window object for onclick access
        window.generateMemberPolicy = function(memberNo) {
            window.open(`generate_policy.php?type=member&id=${memberNo}`, '_blank');
        };

        window.generateFamilyPolicy = function(familyNo) {
            window.open(`generate_policy.php?type=family&id=${familyNo}`, '_blank');
        };
    });
    </script>
</body>
</html>