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

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Not authorized']);
    exit;
}

$family_no = $_GET['family_no'] ?? '';
if (empty($family_no)) {
    header('Location: policy_search.php');
    exit();
}

try {
    // Fetch policy details
    $sql = "SELECT p.*, c.corporate, c.scheme  
            FROM principal_applicant p
            JOIN corporate c ON p.corp_id = c.corp_id 
            WHERE p.family_no = ?";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $family_no);
    $stmt->execute();
    $policy = $stmt->get_result()->fetch_assoc();
    
    if (!$policy) {
        throw new Exception('Policy not found');
    }

    // Fetch members
    $sql = "SELECT m.*, mb.benefit, mb.limit, mb.status as benefit_status 
            FROM member_info m
            LEFT JOIN member_benefits mb ON m.member_no = mb.member_no
            WHERE m.family_no = ? 
            ORDER BY m.relation_to_principal";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('s', $family_no);
    $stmt->execute();
    $members = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

} catch (Exception $e) {
    $_SESSION['error'] = $e->getMessage();
    header('Location: view_policy.php?family_no=' . $family_no);
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Policy')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Policies', 'title' => 'Edit Policy')); ?>

                    <div class="row">
                        <div class="col-xxl-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Policy Details</h4>
                                </div>
                                
                                <div class="card-body">
                                    <form id="editPolicyForm" method="POST" action="save_policy.php">
                                        <input type="hidden" name="family_no" value="<?php echo $family_no; ?>">
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label class="form-label">Corporate</label>
                                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($policy['corporate']); ?>" readonly>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label class="form-label">Scheme</label>
                                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($policy['scheme']); ?>" readonly>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label class="form-label">Family Number</label>
                                                <input type="text" class="form-control" value="<?php echo htmlspecialchars($family_no); ?>" readonly>
                                            </div>
                                        </div>

                                        <!-- Principal Details -->
                                        <h5 class="mb-3">Principal Details</h5>
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label class="form-label">Surname</label>
                                                <input type="text" class="form-control" name="surname" value="<?php echo htmlspecialchars($policy['surname']); ?>" required>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label class="form-label">First Name</label>
                                                <input type="text" class="form-control" name="first_name" value="<?php echo htmlspecialchars($policy['first_name']); ?>" required>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label class="form-label">Other Names</label>
                                                <input type="text" class="form-control" name="other_names" value="<?php echo htmlspecialchars($policy['other_names']); ?>">
                                            </div>
                                        </div>

                                        <!-- Contact Details -->
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label class="form-label">Mobile Number</label>
                                                <input type="tel" class="form-control" name="mobile_no" value="<?php echo htmlspecialchars($policy['mobile_no']); ?>">
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label class="form-label">Email</label>
                                                <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($policy['email']); ?>">
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label class="form-label">Postal Address</label>
                                                <input type="text" class="form-control" name="postal_add" value="<?php echo htmlspecialchars($policy['postal_add']); ?>">
                                            </div>
                                        </div>

                                        <!-- Members Table -->
                                        <h5 class="mb-3">Members</h5>
                                        <div class="table-responsive">
                                            <table class="table table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>Member No</th>
                                                        <th>Name</th>
                                                        <th>Relation</th>
                                                        <th>Benefits</th>
                                                        <th>Status</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($members as $member): ?>
                                                    <tr>
                                                        <td><?php echo htmlspecialchars($member['member_no']); ?></td>
                                                        <td><?php echo htmlspecialchars($member['surname'] . ' ' . $member['first_name']); ?></td>
                                                        <td>
                                                            <?php
                                                            $relations = [
                                                                1 => 'Principal',
                                                                2 => 'Spouse',
                                                                3 => 'Child',
                                                                4 => 'Parent'
                                                            ];
                                                            echo $relations[$member['relation_to_principal']] ?? 'Other';
                                                            ?>
                                                        </td>
                                                        <td>
                                                            <?php if ($member['benefit']): ?>
                                                                <?php echo htmlspecialchars($member['benefit']); ?> - 
                                                                <?php echo number_format($member['limit'], 2); ?>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <span class="badge bg-<?php echo $member['status'] == 1 ? 'success' : 'danger'; ?>">
                                                                <?php echo $member['status'] == 1 ? 'Active' : 'Inactive'; ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <button type="button" class="btn btn-sm btn-info edit-member" 
                                                                    data-member-no="<?php echo $member['member_no']; ?>">
                                                                Edit
                                                            </button>
                                                            <?php if ($member['relation_to_principal'] != 1): ?>
                                                            <button type="button" class="btn btn-sm btn-danger delete-member"
                                                                    data-member-no="<?php echo $member['member_no']; ?>">
                                                                Delete
                                                            </button>
                                                            <?php endif; ?>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>

                                        <div class="mt-3">
                                            <button type="submit" class="btn btn-primary">Save Changes</button>
                                            <a href="view_policy.php?family_no=<?php echo $family_no; ?>" class="btn btn-light">Cancel</a>
                                        </div>
                                    </form>
                                </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).ready(function() {
            // Handle member editing
            $('.edit-member').click(function() {
                const memberNo = $(this).data('member-no');
                window.location.href = 'edit_member.php?member_no=' + memberNo;
            });

            // Handle member deletion
            $('.delete-member').click(function() {
                const memberNo = $(this).data('member-no');
                
                if (confirm('Are you sure you want to delete this member?')) {
                    $.post('delete_member.php', {
                        member_no: memberNo
                    }, function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert(response.error || 'Failed to delete member');
                        }
                    });
                }
            });

            // Form submission
            $('#editPolicyForm').submit(function(e) {
                e.preventDefault();
                
                $.post('save_policy.php', $(this).serialize(), function(response) {
                    if (response.success) {
                        window.location.href = 'view_policy.php?family_no=<?php echo $family_no; ?>';
                    } else {
                        alert(response.error || 'Failed to save changes');
                    }
                });
            });
        });
    </script>
</body>
</html>