<?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'];

$success_message = '';
$error_message = '';

// Get policy ID from URL or form
$policy_id = $_GET['policy_id'] ?? $_POST['policy_id'] ?? null;

// Handle endorsement creation
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'create_endorsement') {
    try {
        $conn->begin_transaction();
        
        $policy_id = $_POST['policy_id'];
        $endorsement_type = $_POST['endorsement_type'];
        $description = $_POST['description'];
        $effective_date = $_POST['effective_date'];
        $premium_adjustment = $_POST['premium_adjustment'] ?? 0;
        $old_values = !empty($_POST['old_values']) ? json_encode($_POST['old_values']) : null;
        $new_values = !empty($_POST['new_values']) ? json_encode($_POST['new_values']) : null;
        
        // Generate endorsement number
        $endorsement_number = 'END-' . date('Y') . '-' . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
        
        // Insert endorsement
        $sql = "INSERT INTO policy_endorsements (
            endorsement_number, policy_id, endorsement_type, description,
            effective_date, old_values, new_values, premium_adjustment,
            processed_by, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING')";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sisssssdi", 
            $endorsement_number, $policy_id, $endorsement_type, $description,
            $effective_date, $old_values, $new_values, $premium_adjustment, $user_id
        );
        
        if ($stmt->execute()) {
            $endorsement_id = $conn->insert_id;
            
            // If premium adjustment, update policy premium
            if ($premium_adjustment != 0) {
                $update_sql = "UPDATE policies SET premium_amount = premium_amount + ? WHERE policy_id = ?";
                $update_stmt = $conn->prepare($update_sql);
                $update_stmt->bind_param("di", $premium_adjustment, $policy_id);
                $update_stmt->execute();
            }
            
            // Log activity
            $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) VALUES (?, 'CREATE', 'ENDORSEMENT', ?, ?)";
            $log_stmt = $conn->prepare($log_sql);
            $log_data = json_encode(['endorsement_number' => $endorsement_number, 'policy_id' => $policy_id]);
            $log_stmt->bind_param("iis", $user_id, $endorsement_id, $log_data);
            $log_stmt->execute();
            
            $conn->commit();
            $success_message = "Endorsement {$endorsement_number} created successfully!";
        } else {
            throw new Exception("Failed to create endorsement");
        }
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = "Error creating endorsement: " . $e->getMessage();
    }
}

// Handle endorsement approval
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'approve_endorsement') {
    try {
        $endorsement_id = $_POST['endorsement_id'];
        
        $sql = "UPDATE policy_endorsements SET status = 'APPROVED', approved_by = ?, approved_at = NOW() WHERE endorsement_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ii", $user_id, $endorsement_id);
        
        if ($stmt->execute()) {
            $success_message = "Endorsement approved successfully!";
        } else {
            $error_message = "Failed to approve endorsement.";
        }
    } catch (Exception $e) {
        $error_message = "Error approving endorsement: " . $e->getMessage();
    }
}

// Get policy details if policy_id is provided
$policy = null;
if ($policy_id) {
    $policy_sql = "SELECT p.*, c.first_name, c.last_name, c.customer_number,
                          ip.product_name, pc.category_name, ic.company_name
                   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
                   WHERE p.policy_id = ?";
    $policy_stmt = $conn->prepare($policy_sql);
    $policy_stmt->bind_param("i", $policy_id);
    $policy_stmt->execute();
    $policy = $policy_stmt->get_result()->fetch_assoc();
}

// Get endorsements for the policy
$endorsements_result = null;
if ($policy_id) {
    $endorsements_sql = "SELECT pe.*, 
                                u1.full_name as processed_by_name,
                                u2.full_name as approved_by_name
                         FROM policy_endorsements pe
                         LEFT JOIN users u1 ON pe.processed_by = u1.user_id
                         LEFT JOIN users u2 ON pe.approved_by = u2.user_id
                         WHERE pe.policy_id = ?
                         ORDER BY pe.created_at DESC";
    $endorsements_stmt = $conn->prepare($endorsements_sql);
    $endorsements_stmt->bind_param("i", $policy_id);
    $endorsements_stmt->execute();
    $endorsements_result = $endorsements_stmt->get_result();
}

// Get recent endorsements (if no specific policy)
if (!$policy_id) {
    $recent_endorsements_sql = "SELECT pe.*, p.policy_number,
                                       c.first_name, c.last_name,
                                       u1.full_name as processed_by_name,
                                       u2.full_name as approved_by_name
                                FROM policy_endorsements pe
                                LEFT JOIN policies p ON pe.policy_id = p.policy_id
                                LEFT JOIN customers c ON p.customer_id = c.customer_id
                                LEFT JOIN users u1 ON pe.processed_by = u1.user_id
                                LEFT JOIN users u2 ON pe.approved_by = u2.user_id
                                " . ($role_name == 'Insurance Agent' ? "WHERE p.agent_id = $user_id" : "") . "
                                ORDER BY pe.created_at DESC
                                LIMIT 50";
    $recent_endorsements_result = $conn->query($recent_endorsements_sql);
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Policy Endorsements')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
    <style>
        .endorsement-card {
            transition: all 0.3s ease;
            border: 1px solid #e9ecef;
        }
        .endorsement-card:hover {
            box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
        }
        .endorsement-type-badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
        }
        .policy-info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
        }
    </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">Policy Endorsements</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"><a href="list_policies.php">Policies</a></li>
                                        <li class="breadcrumb-item active">Endorsements</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if ($success_message): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="ri-check-line me-2"></i><?php echo $success_message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="ri-error-warning-line me-2"></i><?php echo $error_message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Policy Information (if specific policy) -->
                    <?php if ($policy): ?>
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card policy-info-card">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-8">
                                            <h5 class="text-white mb-2">
                                                <i class="ri-file-text-line me-2"></i>
                                                Policy: <?php echo $policy['policy_number']; ?>
                                            </h5>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <p class="text-white-50 mb-1">Customer</p>
                                                    <p class="text-white mb-0">
                                                        <?php echo $policy['first_name'] . ' ' . $policy['last_name']; ?>
                                                        (<?php echo $policy['customer_number']; ?>)
                                                    </p>
                                                </div>
                                                <div class="col-md-6">
                                                    <p class="text-white-50 mb-1">Product</p>
                                                    <p class="text-white mb-0">
                                                        <?php echo $policy['product_name']; ?>
                                                        <span class="badge bg-white text-primary ms-2">
                                                            <?php echo $policy['category_name']; ?>
                                                        </span>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-4 text-md-end">
                                            <p class="text-white-50 mb-1">Current Premium</p>
                                            <h4 class="text-white mb-2">KSH <?php echo number_format($policy['premium_amount'], 2); ?></h4>
                                            <p class="text-white-50 mb-0">Status: 
                                                <span class="badge bg-white text-primary">
                                                    <?php echo ucfirst(strtolower($policy['status'])); ?>
                                                </span>
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Create New Endorsement -->
                        <div class="col-xl-4 mb-4">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-file-edit-line me-2"></i>Create New Endorsement
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST" id="endorsementForm" novalidate>
                                        <input type="hidden" name="action" value="create_endorsement">
                                        
                                        <!-- Policy Selection (if not from specific policy) -->
                                        <?php if (!$policy_id): ?>
                                        <div class="mb-3">
                                            <label for="policy_search" class="form-label">Search Policy <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="policy_search" 
                                                   placeholder="Enter policy number or customer name" required>
                                            <input type="hidden" name="policy_id" id="selected_policy_id" required>
                                            <div class="invalid-feedback">Please select a policy.</div>
                                        </div>
                                        <?php else: ?>
                                        <input type="hidden" name="policy_id" value="<?php echo $policy_id; ?>">
                                        <?php endif; ?>

                                        <!-- Endorsement Type -->
                                        <div class="mb-3">
                                            <label for="endorsement_type" class="form-label">Endorsement Type <span class="text-danger">*</span></label>
                                            <select class="form-select" name="endorsement_type" required>
                                                <option value="">Select Type</option>
                                                <option value="ADDITION">Addition</option>
                                                <option value="REMOVAL">Removal</option>
                                                <option value="AMENDMENT">Amendment</option>
                                                <option value="INCREASE">Increase</option>
                                                <option value="DECREASE">Decrease</option>
                                                <option value="CORRECTION">Correction</option>
                                            </select>
                                            <div class="invalid-feedback">Please select endorsement type.</div>
                                        </div>

                                        <!-- Description -->
                                        <div class="mb-3">
                                            <label for="description" class="form-label">Description <span class="text-danger">*</span></label>
                                            <textarea class="form-control" name="description" rows="3" 
                                                      placeholder="Describe the changes being made..." required></textarea>
                                            <div class="invalid-feedback">Please provide a description.</div>
                                        </div>

                                        <!-- Effective Date -->
                                        <div class="mb-3">
                                            <label for="effective_date" class="form-label">Effective Date <span class="text-danger">*</span></label>
                                            <input type="date" class="form-control" name="effective_date" 
                                                   value="<?php echo date('Y-m-d'); ?>" required>
                                            <div class="invalid-feedback">Please select effective date.</div>
                                        </div>

                                        <!-- Premium Adjustment -->
                                        <div class="mb-3">
                                            <label for="premium_adjustment" class="form-label">Premium Adjustment (KSH)</label>
                                            <input type="number" class="form-control" name="premium_adjustment" 
                                                   step="0.01" value="0" placeholder="0.00">
                                            <div class="form-text">Enter positive for increase, negative for decrease</div>
                                        </div>

                                        <!-- Old Values -->
                                        <div class="mb-3">
                                            <label for="old_values" class="form-label">Previous Values</label>
                                            <textarea class="form-control" name="old_values" rows="2" 
                                                      placeholder="Previous policy details (JSON format)"></textarea>
                                        </div>

                                        <!-- New Values -->
                                        <div class="mb-3">
                                            <label for="new_values" class="form-label">New Values</label>
                                            <textarea class="form-control" name="new_values" rows="2" 
                                                      placeholder="Updated policy details (JSON format)"></textarea>
                                        </div>

                                        <div class="text-end">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line me-1"></i> Create Endorsement
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Endorsements List -->
                        <div class="col-xl-8">
                            <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>
                                        <?php echo $policy_id ? 'Policy Endorsements' : 'Recent Endorsements'; ?>
                                    </h5>
                                    <?php if (!$policy_id): ?>
                                    <a href="list_policies.php" class="btn btn-light btn-sm">
                                        <i class="ri-arrow-left-line me-1"></i> Back to Policies
                                    </a>
                                    <?php endif; ?>
                                </div>
                                <div class="card-body p-0">
                                    <?php 
                                    $result_to_use = $policy_id ? $endorsements_result : $recent_endorsements_result;
                                    if ($result_to_use && $result_to_use->num_rows > 0): 
                                    ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover align-middle mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Endorsement Details</th>
                                                    <?php if (!$policy_id): ?>
                                                    <th>Policy</th>
                                                    <?php endif; ?>
                                                    <th>Type & Description</th>
                                                    <th>Adjustment</th>
                                                    <th>Processed By</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($endorsement = $result_to_use->fetch_assoc()): 
                                                    $status_class = match($endorsement['status']) {
                                                        'APPROVED' => 'success',
                                                        'PENDING' => 'warning',
                                                        'REJECTED' => 'danger',
                                                        default => 'info'
                                                    };
                                                    
                                                    $type_class = match($endorsement['endorsement_type']) {
                                                        'ADDITION' => 'primary',
                                                        'REMOVAL' => 'danger',
                                                        'AMENDMENT' => 'info',
                                                        'INCREASE' => 'success',
                                                        'DECREASE' => 'warning',
                                                        'CORRECTION' => 'secondary',
                                                        default => 'light'
                                                    };
                                                ?>
                                                <tr class="endorsement-card">
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-1"><?php echo $endorsement['endorsement_number']; ?></h6>
                                                            <p class="text-muted mb-0 small">
                                                                Effective: <?php echo date('M j, Y', strtotime($endorsement['effective_date'])); ?>
                                                            </p>
                                                            <p class="text-muted mb-0 small">
                                                                Created: <?php echo date('M j, Y', strtotime($endorsement['created_at'])); ?>
                                                            </p>
                                                        </div>
                                                    </td>
                                                    
                                                    <?php if (!$policy_id): ?>
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-1">
                                                                <a href="view_policy.php?id=<?php echo $endorsement['policy_id']; ?>" 
                                                                   class="text-primary text-decoration-none">
                                                                    <?php echo $endorsement['policy_number']; ?>
                                                                </a>
                                                            </h6>
                                                            <p class="text-muted mb-0 small">
                                                                <?php echo $endorsement['first_name'] . ' ' . $endorsement['last_name']; ?>
                                                            </p>
                                                        </div>
                                                    </td>
                                                    <?php endif; ?>
                                                    
                                                    <td>
                                                        <div>
                                                            <span class="badge bg-<?php echo $type_class; ?> endorsement-type-badge mb-2">
                                                                <?php echo ucfirst(strtolower($endorsement['endorsement_type'])); ?>
                                                            </span>
                                                            <p class="mb-0 small"><?php echo $endorsement['description']; ?></p>
                                                        </div>
                                                    </td>
                                                    
                                                    <td>
                                                        <?php if ($endorsement['premium_adjustment'] != 0): ?>
                                                        <div class="text-center">
                                                            <h6 class="mb-0 <?php echo $endorsement['premium_adjustment'] > 0 ? 'text-success' : 'text-danger'; ?>">
                                                                <?php echo $endorsement['premium_adjustment'] > 0 ? '+' : ''; ?>
                                                                KSH <?php echo number_format($endorsement['premium_adjustment'], 2); ?>
                                                            </h6>
                                                        </div>
                                                        <?php else: ?>
                                                        <div class="text-center text-muted">
                                                            <span>No Change</span>
                                                        </div>
                                                        <?php endif; ?>
                                                    </td>
                                                    
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-0"><?php echo $endorsement['processed_by_name']; ?></h6>
                                                            <?php if ($endorsement['approved_by_name']): ?>
                                                            <p class="text-muted mb-0 small">
                                                                Approved by: <?php echo $endorsement['approved_by_name']; ?>
                                                            </p>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    
                                                    <td>
                                                        <span class="badge bg-<?php echo $status_class; ?>">
                                                            <?php echo ucfirst(strtolower($endorsement['status'])); ?>
                                                        </span>
                                                        <?php if ($endorsement['approved_at']): ?>
                                                        <p class="text-muted mb-0 small">
                                                            <?php echo date('M j, Y', strtotime($endorsement['approved_at'])); ?>
                                                        </p>
                                                        <?php endif; ?>
                                                    </td>
                                                    
                                                    <td>
                                                        <div class="dropdown">
                                                            <button class="btn btn-light btn-sm dropdown-toggle" type="button" 
                                                                    data-bs-toggle="dropdown">
                                                                <i class="ri-more-2-fill"></i>
                                                            </button>
                                                            <ul class="dropdown-menu">
                                                                <li>
                                                                    <a class="dropdown-item" href="#" 
                                                                       onclick="viewEndorsement(<?php echo $endorsement['endorsement_id']; ?>)">
                                                                        <i class="ri-eye-line me-2"></i>View Details
                                                                    </a>
                                                                </li>
                                                                <?php if ($endorsement['status'] == 'PENDING' && hasPermission('policies_approve')): ?>
                                                                <li>
                                                                    <form method="POST" class="d-inline">
                                                                        <input type="hidden" name="action" value="approve_endorsement">
                                                                        <input type="hidden" name="endorsement_id" value="<?php echo $endorsement['endorsement_id']; ?>">
                                                                        <button type="submit" class="dropdown-item text-success">
                                                                            <i class="ri-check-line me-2"></i>Approve
                                                                        </button>
                                                                    </form>
                                                                </li>
                                                                <?php endif; ?>
                                                                <li><hr class="dropdown-divider"></li>
                                                                <li>
                                                                    <a class="dropdown-item" href="view_policy.php?id=<?php echo $endorsement['policy_id']; ?>">
                                                                        <i class="ri-file-text-line me-2"></i>View Policy
                                                                    </a>
                                                                </li>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    
                                    <?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-edit-line fs-1"></i>
                                            </div>
                                        </div>
                                        <h5>No endorsements found</h5>
                                        <p class="text-muted">
                                            <?php echo $policy_id ? 'This policy has no endorsements yet.' : 'No recent endorsements available.'; ?>
                                        </p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <!-- Endorsement Details Modal -->
    <div class="modal fade" id="endorsementModal" tabindex="-1" aria-labelledby="endorsementModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="endorsementModalLabel">
                        <i class="ri-file-edit-line me-2"></i>Endorsement Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="endorsementModalBody">
                    <!-- Content will be loaded here -->
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

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

            // Policy search autocomplete (if not from specific policy)
            <?php if (!$policy_id): ?>
            $('#policy_search').on('input', function() {
                const query = $(this).val();
                if (query.length > 2) {
                    // Implement AJAX search for policies
                    searchPolicies(query);
                }
            });
            <?php endif; ?>

            // Form validation
            $('#endorsementForm').on('submit', function(e) {
                if (!this.checkValidity()) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                $(this).addClass('was-validated');
            });
        });

        function searchPolicies(query) {
            // AJAX call to search policies
            $.ajax({
                url: 'search_policies.php',
                method: 'GET',
                data: { q: query },
                success: function(response) {
                    // Handle search results
                    console.log(response);
                }
            });
        }

        function viewEndorsement(endorsementId) {
            // Load endorsement details in modal
            $.ajax({
                url: 'get_endorsement_details.php',
                method: 'GET',
                data: { id: endorsementId },
                success: function(response) {
                    $('#endorsementModalBody').html(response);
                    $('#endorsementModal').modal('show');
                },
                error: function() {
                    alert('Failed to load endorsement details');
                }
            });
        }
    </script>
</body>
</html>