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

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

// Get quotation number from URL
$quotation_no = $_GET['quotation_no'] ?? '';

if (empty($quotation_no)) {
    header('Location: quotations_list.php');
    exit();
}

// Fetch quotation details with corporate info
$sql = "SELECT q.*, 
               c.corporate as corporate_name,
               c.scheme,
               c.policy_no,
               COUNT(qm.member_id) as member_count,
               MIN(qm.relation = 'principal') as has_principal
        FROM quotations q
        JOIN corporate c ON q.corp_id = c.corp_id
        LEFT JOIN quotation_members qm ON q.quotation_no = qm.quotation_no
        WHERE q.quotation_no = ?
        GROUP BY q.quotation_no";

$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $quotation_no);
$stmt->execute();
$quotation = $stmt->get_result()->fetch_assoc();

// Validate quotation
if (!$quotation) {
    header('Location: quotations_list.php');
    exit();
}

// Check if quotation can be converted
if ($quotation['status'] !== 'PENDING') {
    $_SESSION['error'] = 'This quotation has already been processed';
    header('Location: quotations_list.php');
    exit();
}

if (strtotime($quotation['valid_until']) < time()) {
    $_SESSION['error'] = 'This quotation has expired';
    header('Location: quotations_list.php');
    exit();
}

if (!$quotation['has_principal']) {
    $_SESSION['error'] = 'Quotation must have a principal member';
    header('Location: quotations_list.php');
    exit();
}

// Fetch members and their benefits
$sql = "SELECT qm.*, 
               qmb.benefit_code,
               qmb.premium,
               qmb.limit_amount,
               b.benefit as benefit_name
        FROM quotation_members qm
        JOIN quotation_member_benefits qmb ON qm.member_id = qmb.member_id
        JOIN benefit b ON qmb.benefit_code = b.code
        WHERE qm.quotation_no = ?
        ORDER BY qm.relation = 'principal' DESC, qm.member_id";

$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $quotation_no);
$stmt->execute();
$result = $stmt->get_result();

$members = [];
while ($row = $result->fetch_assoc()) {
    $member_id = $row['member_id'];
    if (!isset($members[$member_id])) {
        $members[$member_id] = [
            'id' => $member_id,
            'relation' => $row['relation'],
            'age' => $row['age'],
            'premium' => $row['premium'],
            'benefits' => []
        ];
    }
    $members[$member_id]['benefits'][] = [
        'code' => $row['benefit_code'],
        'name' => $row['benefit_name'],
        'limit' => $row['limit_amount'],
        'premium' => $row['premium']
    ];
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Convert Quotation to Policy')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .quotation-card {
            background-color: #f8f9fa;
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        .member-card {
            background-color: white;
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
            padding: 1rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        .member-card:hover {
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .benefit-row {
            padding: 0.75rem;
            border-bottom: 1px solid #eee;
        }
        .benefit-row:last-child {
            border-bottom: none;
        }
        .conversion-summary {
            background-color: #e8f4ff;
            border-radius: 0.5rem;
            padding: 1.5rem;
        }
    </style>
</head>

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

                    <div class="row">
                        <div class="col-lg-12">
                            <!-- Quotation Details Card -->
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Quotation Details</h4>
                                    <div class="flex-shrink-0">
                                        <button type="button" class="btn btn-primary btn-sm" id="convertBtn">
                                            <i class="ri-arrow-right-line align-middle me-1"></i> Convert to Policy
                                        </button>
                                        <a href="quotations_list.php" class="btn btn-light btn-sm ms-2">
                                            <i class="ri-arrow-left-line align-middle me-1"></i> Back
                                        </a>
                                    </div>
                                </div>

                                <div class="card-body">
                                    <!-- Basic Info -->
                                    <div class="quotation-card">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <table class="table table-sm table-borderless mb-0">
                                                    <tr>
                                                        <th width="150">Quotation No:</th>
                                                        <td><?php echo $quotation['quotation_no']; ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Corporate:</th>
                                                        <td><?php echo $quotation['corporate_name']; ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Scheme:</th>
                                                        <td><?php echo $quotation['scheme']; ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Members:</th>
                                                        <td><?php echo $quotation['member_count']; ?></td>
                                                    </tr>
                                                </table>
                                            </div>
                                            <div class="col-md-6">
                                                <table class="table table-sm table-borderless mb-0">
                                                    <tr>
                                                        <th width="150">Total Premium:</th>
                                                        <td><?php echo number_format($quotation['total_premium'], 2); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Policy Number:</th>
                                                        <td><?php echo $quotation['policy_no']; ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Valid Until:</th>
                                                        <td><?php echo date('d M Y', strtotime($quotation['valid_until'])); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <th>Status:</th>
                                                        <td>
                                                            <span class="badge bg-warning">
                                                                <?php echo $quotation['status']; ?>
                                                            </span>
                                                        </td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Conversion Summary -->
                                    <div class="conversion-summary mb-4">
                                        <h5 class="mb-3">Conversion Summary</h5>
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Cover Start Date</label>
                                                    <input type="date" class="form-control" id="startDate" 
                                                           value="<?php echo date('Y-m-d'); ?>" required>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Cover End Date</label>
                                                    <input type="date" class="form-control" id="endDate" readonly>
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Policy Status</label>
                                                    <select class="form-select" id="policyStatus" required>
                                                        <option value="ACTIVE">Active</option>
                                                        <option value="PENDING">Pending Payment</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Members List -->
                                    <h5 class="mb-3">Members and Benefits</h5>
                                    <?php foreach ($members as $member): ?>
                                        <div class="member-card">
                                            <div class="d-flex justify-content-between align-items-center mb-3">
                                                <h6 class="mb-0">
                                                    <?php echo ucfirst($member['relation']); ?>
                                                    <span class="text-muted ms-2">(Age: <?php echo $member['age']; ?>)</span>
                                                </h6>
                                                <span class="badge bg-primary">
                                                    Premium: <?php echo number_format($member['premium'], 2); ?>
                                                </span>
                                            </div>
                                            <div class="benefits-list">
                                                <?php foreach ($member['benefits'] as $benefit): ?>
                                                    <div class="benefit-row d-flex justify-content-between align-items-center">
                                                        <div>
                                                            <strong><?php echo htmlspecialchars($benefit['name']); ?></strong>
                                                            <div class="text-muted small">
                                                                Limit: <?php echo number_format($benefit['limit'], 2); ?>
                                                            </div>
                                                        </div>
                                                        <div class="text-end">
                                                            Premium: <?php echo number_format($benefit['premium'], 2); ?>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </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() {
            // Initialize variables
            const startDateInput = document.getElementById('startDate');
            const endDateInput = document.getElementById('endDate');
            const policyStatusSelect = document.getElementById('policyStatus');
            const convertBtn = document.getElementById('convertBtn');

            // Update end date when start date changes
            startDateInput.addEventListener('change', function() {
                const startDate = new Date(this.value);
                const endDate = new Date(startDate);
                endDate.setFullYear(endDate.getFullYear() + 1);
                endDate.setDate(endDate.getDate() - 1);
                endDateInput.value = endDate.toISOString().split('T')[0];
            });

            // Trigger initial end date calculation
            startDateInput.dispatchEvent(new Event('change'));

            // Handle conversion button click
            convertBtn.addEventListener('click', function() {
                // Validate inputs
                if (!startDateInput.value || !endDateInput.value || !policyStatusSelect.value) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Missing Information',
                        text: 'Please fill in all required fields'
                    });
                    return;
                }

                // Confirm conversion
                Swal.fire({
                    title: 'Convert to Policy?',
                    text: 'This action will convert the quotation into an active policy. Continue?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, Convert',
                    cancelButtonText: 'Cancel',
                    confirmButtonColor: '#28a745'
                }).then((result) => {
                    if (result.isConfirmed) {
                        convertQuotation();
                    }
                });
            });

            // Handle conversion process
            function convertQuotation() {
                // Show loading state
                Swal.fire({
                    title: 'Converting...',
                    text: 'Please wait while we process your request',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // Submit conversion request
                fetch('quotation_to_policy.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        quotation_no: '<?php echo $quotation_no; ?>',
                        start_date: startDateInput.value,
                        end_date: endDateInput.value,
                        policy_status: policyStatusSelect.value,
                        corp_id: '<?php echo $quotation['corp_id']; ?>',
                        scheme: '<?php echo $quotation['scheme']; ?>'
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.error || 'Failed to convert quotation');
                    }

                    // Show success message
                    Swal.fire({
                        icon: 'success',
                        title: 'Conversion Successful!',
                        text: 'The quotation has been converted to a policy',
                        confirmButtonText: 'View Policy',
                        showCancelButton: true,
                        cancelButtonText: 'Return to List'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location.href = 'view_policy.php?family_no=' + data.family_no;
                        } else {
                            window.location.href = 'quotations_list.php?success=' + 
                                encodeURIComponent('Quotation successfully converted to policy');
                        }
                    });
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Conversion Failed',
                        text: error.message || 'Failed to convert quotation to policy',
                        footer: '<a href="quotations_list.php">Return to Quotations List</a>'
                    });
                });
            }

            // Add validation for cover dates
            startDateInput.addEventListener('input', validateDates);
            
            function validateDates() {
                const startDate = new Date(startDateInput.value);
                const today = new Date();
                today.setHours(0, 0, 0, 0);

                // Prevent backdating beyond 30 days
                const thirtyDaysAgo = new Date();
                thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
                thirtyDaysAgo.setHours(0, 0, 0, 0);

                if (startDate < thirtyDaysAgo) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Invalid Start Date',
                        text: 'Cover cannot be backdated more than 30 days'
                    });
                    startDateInput.value = today.toISOString().split('T')[0];
                    startDateInput.dispatchEvent(new Event('change'));
                    return false;
                }

                // Update end date and validate period
                const endDate = new Date(startDate);
                endDate.setFullYear(endDate.getFullYear() + 1);
                endDate.setDate(endDate.getDate() - 1);
                endDateInput.value = endDate.toISOString().split('T')[0];

                return true;
            }

            // Handle policy status change
            policyStatusSelect.addEventListener('change', function() {
                const warningDiv = document.getElementById('pendingWarning');
                if (this.value === 'PENDING' && !warningDiv) {
                    const warning = document.createElement('div');
                    warning.id = 'pendingWarning';
                    warning.className = 'alert alert-warning mt-3';
                    warning.innerHTML = `
                        <i class="ri-alert-line me-2"></i>
                        <strong>Note:</strong> Policy will be inactive until payment is received
                    `;
                    this.parentNode.appendChild(warning);
                } else if (this.value !== 'PENDING' && warningDiv) {
                    warningDiv.remove();
                }
            });
        });
    </script>
</body>
</html>