<?php
session_start();
require_once 'layouts/dbconn.php';
require_once 'includes/functions.php';

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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

$user_id = $_SESSION['user_id'];
$success_message = '';
$error_message = '';

// Get company ID from URL
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: list_insurers.php');
    exit();
}

$company_id = (int)$_GET['id'];

// Get existing company data
$sql = "SELECT * FROM insurance_companies WHERE company_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $company_id);
$stmt->execute();
$company = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$company) {
    header('Location: list_insurers.php');
    exit();
}

// Parse commission structure
$commission_structure = [];
if ($company['commission_structure']) {
    $commission_structure = json_decode($company['commission_structure'], true) ?: [];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        // Validate required fields
        $required_fields = ['company_name', 'company_code', 'contact_person', 'email', 'phone'];
        foreach ($required_fields as $field) {
            if (empty($_POST[$field])) {
                throw new Exception("Please fill in all required fields.");
            }
        }

        // Check if company code already exists (excluding current company)
        $check_code_sql = "SELECT company_id FROM insurance_companies WHERE company_code = ? AND company_id != ?";
        $check_stmt = $conn->prepare($check_code_sql);
        $check_stmt->bind_param("si", $_POST['company_code'], $company_id);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            throw new Exception("Company code already exists. Please use a different code.");
        }
        $check_stmt->close();

        // Check if company name already exists (excluding current company)
        $check_name_sql = "SELECT company_id FROM insurance_companies WHERE company_name = ? AND company_id != ?";
        $check_stmt = $conn->prepare($check_name_sql);
        $check_stmt->bind_param("si", $_POST['company_name'], $company_id);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            throw new Exception("Company name already exists. Please use a different name.");
        }
        $check_stmt->close();

        // Store old values for logging
        $old_values = [
            'company_name' => $company['company_name'],
            'company_code' => $company['company_code'],
            'contact_person' => $company['contact_person'],
            'email' => $company['email'],
            'integration_type' => $company['integration_type'],
            'is_active' => $company['is_active']
        ];

        // Prepare data for update
        $company_name = trim($_POST['company_name']);
        $company_code = strtoupper(trim($_POST['company_code']));
        $short_name = !empty($_POST['short_name']) ? trim($_POST['short_name']) : null;
        $license_number = !empty($_POST['license_number']) ? trim($_POST['license_number']) : null;
        $contact_person = trim($_POST['contact_person']);
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);
        $address = !empty($_POST['address']) ? trim($_POST['address']) : null;
        $website = !empty($_POST['website']) ? trim($_POST['website']) : null;
        $integration_type = $_POST['integration_type'];
        $api_endpoint = !empty($_POST['api_endpoint']) ? trim($_POST['api_endpoint']) : null;
        $payment_terms = !empty($_POST['payment_terms']) ? trim($_POST['payment_terms']) : null;
        $is_active = isset($_POST['is_active']) ? 1 : 0;

        // Process commission structure
        $commission_structure_new = [];
        if (!empty($_POST['health_commission'])) {
            $commission_structure_new['HEALTH'] = (float)$_POST['health_commission'];
        }
        if (!empty($_POST['motor_commission'])) {
            $commission_structure_new['MOTOR'] = (float)$_POST['motor_commission'];
        }
        if (!empty($_POST['life_commission'])) {
            $commission_structure_new['LIFE'] = (float)$_POST['life_commission'];
        }
        if (!empty($_POST['property_commission'])) {
            $commission_structure_new['PROPERTY'] = (float)$_POST['property_commission'];
        }
        if (!empty($_POST['travel_commission'])) {
            $commission_structure_new['TRAVEL'] = (float)$_POST['travel_commission'];
        }
        if (!empty($_POST['micro_commission'])) {
            $commission_structure_new['MICRO'] = (float)$_POST['micro_commission'];
        }

        $commission_json = !empty($commission_structure_new) ? json_encode($commission_structure_new) : null;

        // New values for logging
        $new_values = [
            'company_name' => $company_name,
            'company_code' => $company_code,
            'contact_person' => $contact_person,
            'email' => $email,
            'integration_type' => $integration_type,
            'is_active' => $is_active
        ];

        // Update company
        $update_sql = "UPDATE insurance_companies SET 
            company_code = ?, company_name = ?, short_name = ?, license_number = ?, 
            contact_person = ?, email = ?, phone = ?, address = ?, website = ?, 
            api_endpoint = ?, integration_type = ?, commission_structure = ?, 
            payment_terms = ?, is_active = ?, updated_at = NOW()
            WHERE company_id = ?";

        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param("sssssssssssssii", 
            $company_code, $company_name, $short_name, $license_number, $contact_person,
            $email, $phone, $address, $website, $api_endpoint, $integration_type,
            $commission_json, $payment_terms, $is_active, $company_id
        );

        if ($stmt->execute()) {
            // Log activity
            logActivity($conn, $user_id, 'UPDATE', 'INSURER', $company_id, $old_values, $new_values);

            $success_message = "Insurance company '{$company_name}' has been successfully updated.";
            
            // Redirect after successful update
            header("Location: view_insurer.php?id={$company_id}&success=updated");
            exit();
        } else {
            throw new Exception("Failed to update insurance company. Please try again.");
        }

    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Insurance Company - ' . $company['company_name'])); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .form-floating > .form-control {
            padding-top: 1.625rem;
            padding-bottom: 0.625rem;
        }
        
        .form-floating > label {
            padding: 1rem 0.75rem;
        }
        
        .section-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-radius: 15px;
            margin-bottom: 2rem;
        }
        
        .section-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 15px 15px 0 0;
            margin: -1px -1px 0 -1px;
        }
        
        .required-field::after {
            content: " *";
            color: #e74c3c;
            font-weight: bold;
        }
        
        .commission-input {
            max-width: 120px;
        }
    </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">Edit Insurance Company</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_insurers.php">Insurance Companies</a></li>
                                        <li class="breadcrumb-item"><a href="view_insurer.php?id=<?php echo $company_id; ?>"><?php echo htmlspecialchars($company['company_name']); ?></a></li>
                                        <li class="breadcrumb-item active">Edit</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

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

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

                    <form method="POST" id="editInsurerForm" novalidate>
                        <div class="row">
                            <!-- Basic Information -->
                            <div class="col-xl-8">
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-building-line me-2"></i>
                                            Company Information
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-8 mb-3">
                                                <div class="form-floating">
                                                    <input type="text" class="form-control" id="company_name" name="company_name" 
                                                           placeholder="Company Name" required 
                                                           value="<?php echo htmlspecialchars($company['company_name']); ?>">
                                                    <label for="company_name" class="required-field">Company Name</label>
                                                    <div class="invalid-feedback">Please provide a company name.</div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <div class="form-floating">
                                                    <input type="text" class="form-control" id="company_code" name="company_code" 
                                                           placeholder="Company Code" required style="text-transform: uppercase;"
                                                           value="<?php echo htmlspecialchars($company['company_code']); ?>">
                                                    <label for="company_code" class="required-field">Company Code</label>
                                                    <div class="invalid-feedback">Please provide a company code.</div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <div class="form-floating">
                                                    <input type="text" class="form-control" id="short_name" name="short_name" 
                                                           placeholder="Short Name" 
                                                           value="<?php echo htmlspecialchars($company['short_name']); ?>">
                                                    <label for="short_name">Short Name</label>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6 mb-3">
                                                <div class="form-floating">
                                                    <input type="text" class="form-control" id="license_number" name="license_number" 
                                                           placeholder="License Number" 
                                                           value="<?php echo htmlspecialchars($company['license_number']); ?>">
                                                    <label for="license_number">Insurance License Number</label>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <div class="form-floating">
                                                <textarea class="form-control" id="address" name="address" 
                                                          style="height: 100px" placeholder="Company Address"><?php echo htmlspecialchars($company['address']); ?></textarea>
                                                <label for="address">Company Address</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Contact Information -->
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-contacts-line me-2"></i>
                                            Contact Information
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <div class="form-floating">
                                                    <input type="text" class="form-control" id="contact_person" name="contact_person" 
                                                           placeholder="Contact Person" required 
                                                           value="<?php echo htmlspecialchars($company['contact_person']); ?>">
                                                    <label for="contact_person" class="required-field">Contact Person</label>
                                                    <div class="invalid-feedback">Please provide a contact person name.</div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <div class="form-floating">
                                                    <input type="email" class="form-control" id="email" name="email" 
                                                           placeholder="Email" required 
                                                           value="<?php echo htmlspecialchars($company['email']); ?>">
                                                    <label for="email" class="required-field">Email Address</label>
                                                    <div class="invalid-feedback">Please provide a valid email address.</div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <div class="form-floating">
                                                    <input type="tel" class="form-control" id="phone" name="phone" 
                                                           placeholder="Phone" required 
                                                           value="<?php echo htmlspecialchars($company['phone']); ?>">
                                                    <label for="phone" class="required-field">Phone Number</label>
                                                    <div class="invalid-feedback">Please provide a phone number.</div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-12 mb-3">
                                                <div class="form-floating">
                                                    <input type="url" class="form-control" id="website" name="website" 
                                                           placeholder="Website" 
                                                           value="<?php echo htmlspecialchars($company['website']); ?>">
                                                    <label for="website">Website</label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Commission Structure -->
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-percent-line me-2"></i>
                                            Commission Structure
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Health Insurance</label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control commission-input" 
                                                           name="health_commission" min="0" max="100" step="0.01"
                                                           placeholder="0.00" 
                                                           value="<?php echo isset($commission_structure['HEALTH']) ? $commission_structure['HEALTH'] : ''; ?>">
                                                    <span class="input-group-text">%</span>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Motor Insurance</label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control commission-input" 
                                                           name="motor_commission" min="0" max="100" step="0.01"
                                                           placeholder="0.00" 
                                                           value="<?php echo isset($commission_structure['MOTOR']) ? $commission_structure['MOTOR'] : ''; ?>">
                                                    <span class="input-group-text">%</span>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Life Insurance</label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control commission-input" 
                                                           name="life_commission" min="0" max="100" step="0.01"
                                                           placeholder="0.00" 
                                                           value="<?php echo isset($commission_structure['LIFE']) ? $commission_structure['LIFE'] : ''; ?>">
                                                    <span class="input-group-text">%</span>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Property Insurance</label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control commission-input" 
                                                           name="property_commission" min="0" max="100" step="0.01"
                                                           placeholder="0.00" 
                                                           value="<?php echo isset($commission_structure['PROPERTY']) ? $commission_structure['PROPERTY'] : ''; ?>">
                                                    <span class="input-group-text">%</span>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Travel Insurance</label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control commission-input" 
                                                           name="travel_commission" min="0" max="100" step="0.01"
                                                           placeholder="0.00" 
                                                           value="<?php echo isset($commission_structure['TRAVEL']) ? $commission_structure['TRAVEL'] : ''; ?>">
                                                    <span class="input-group-text">%</span>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Micro Insurance</label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control commission-input" 
                                                           name="micro_commission" min="0" max="100" step="0.01"
                                                           placeholder="0.00" 
                                                           value="<?php echo isset($commission_structure['MICRO']) ? $commission_structure['MICRO'] : ''; ?>">
                                                    <span class="input-group-text">%</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Configuration Panel -->
                            <div class="col-xl-4">
                                <!-- Integration Settings -->
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-plug-line me-2"></i>
                                            Integration Settings
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label class="form-label">Integration Type</label>
                                            <select class="form-select" name="integration_type">
                                                <option value="MANUAL" <?php echo $company['integration_type'] == 'MANUAL' ? 'selected' : ''; ?>>Manual Processing</option>
                                                <option value="API" <?php echo $company['integration_type'] == 'API' ? 'selected' : ''; ?>>API Integration</option>
                                                <option value="HYBRID" <?php echo $company['integration_type'] == 'HYBRID' ? 'selected' : ''; ?>>Hybrid (API + Manual)</option>
                                            </select>
                                        </div>

                                        <div class="mb-3" id="api_endpoint_group">
                                            <div class="form-floating">
                                                <input type="url" class="form-control" id="api_endpoint" name="api_endpoint" 
                                                       placeholder="API Endpoint" 
                                                       value="<?php echo htmlspecialchars($company['api_endpoint']); ?>">
                                                <label for="api_endpoint">API Endpoint</label>
                                                <div class="form-text">Required for API integration</div>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" id="is_active" 
                                                       name="is_active" <?php echo $company['is_active'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="is_active">
                                                    Active Company
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Payment Terms -->
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-money-dollar-circle-line me-2"></i>
                                            Payment Terms
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <textarea class="form-control" name="payment_terms" rows="6" 
                                                      placeholder="Enter payment terms and conditions..."><?php echo htmlspecialchars($company['payment_terms']); ?></textarea>
                                            <div class="form-text">Specify commission payment schedule, terms, and conditions</div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Actions -->
                                <div class="card section-card">
                                    <div class="section-header">
                                        <h5 class="mb-0">
                                            <i class="ri-tools-line me-2"></i>
                                            Actions
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="d-grid gap-2">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line me-2"></i>
                                                Update Company
                                            </button>
                                            
                                            <button type="button" class="btn btn-outline-info" onclick="previewChanges()">
                                                <i class="ri-eye-line me-2"></i>
                                                Preview Changes
                                            </button>
                                            
                                            <a href="view_insurer.php?id=<?php echo $company_id; ?>" class="btn btn-secondary">
                                                <i class="ri-arrow-left-line me-2"></i>
                                                Back to Details
                                            </a>
                                            
                                            <a href="list_insurers.php" class="btn btn-outline-secondary">
                                                <i class="ri-list-check me-2"></i>
                                                All Companies
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>

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

    <!-- Changes Preview Modal -->
    <div class="modal fade" id="changesPreviewModal" tabindex="-1" aria-labelledby="changesPreviewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="changesPreviewModalLabel">Preview Changes</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="changesPreviewContent">
                    <!-- Preview content will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" form="editInsurerForm" class="btn btn-primary">Save Changes</button>
                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Form validation
            $('#editInsurerForm').on('submit', function(e) {
                if (!this.checkValidity()) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                this.classList.add('was-validated');
            });
            
            // Convert company code to uppercase
            $('#company_code').on('input', function() {
                this.value = this.value.toUpperCase();
            });
            
            // Toggle API endpoint field based on integration type
            $('[name="integration_type"]').on('change', function() {
                const apiGroup = $('#api_endpoint_group');
                const apiInput = $('#api_endpoint');
                
                if ($(this).val() === 'API' || $(this).val() === 'HYBRID') {
                    apiGroup.show();
                    apiInput.prop('required', true);
                } else {
                    apiGroup.hide();
                    apiInput.prop('required', false);
                }
            });
            
            // Initial toggle
            $('[name="integration_type"]').trigger('change');
        });
        
        function previewChanges() {
            // Original values
            const original = {
                company_name: "<?php echo htmlspecialchars($company['company_name']); ?>",
                company_code: "<?php echo htmlspecialchars($company['company_code']); ?>",
                contact_person: "<?php echo htmlspecialchars($company['contact_person']); ?>",
                email: "<?php echo htmlspecialchars($company['email']); ?>",
                phone: "<?php echo htmlspecialchars($company['phone']); ?>",
                integration_type: "<?php echo htmlspecialchars($company['integration_type']); ?>",
                is_active: <?php echo $company['is_active'] ? 'true' : 'false'; ?>
            };
            
            // Current form values
            const current = {
                company_name: $('#company_name').val(),
                company_code: $('#company_code').val(),
                contact_person: $('#contact_person').val(),
                email: $('#email').val(),
                phone: $('#phone').val(),
                integration_type: $('[name="integration_type"]').val(),
                is_active: $('#is_active').is(':checked')
            };
            
            // Find changes
            let changes = [];
            Object.keys(original).forEach(key => {
                if (original[key] != current[key]) {
                    changes.push({
                        field: key.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase()),
                        old_value: original[key],
                        new_value: current[key]
                    });
                }
            });
            
            let previewHtml = '';
            if (changes.length > 0) {
                previewHtml = `
                    <div class="alert alert-info">
                        <i class="ri-information-line me-2"></i>
                        The following changes will be made:
                    </div>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>Field</th>
                                    <th>Current Value</th>
                                    <th>New Value</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${changes.map(change => `
                                    <tr>
                                        <td><strong>${change.field}</strong></td>
                                        <td class="text-muted">${change.old_value}</td>
                                        <td class="text-primary"><strong>${change.new_value}</strong></td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                `;
            } else {
                previewHtml = `
                    <div class="alert alert-warning">
                        <i class="ri-alert-line me-2"></i>
                        No changes detected. The form values are the same as the current company information.
                    </div>
                `;
            }
            
            $('#changesPreviewContent').html(previewHtml);
            $('#changesPreviewModal').modal('show');
        }
    </script>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>