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

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

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

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $provider_name = trim($_POST['provider_name'] ?? '');
    $provider_code = trim($_POST['provider_code'] ?? '');
    $contact_person = trim($_POST['contact_person'] ?? '');
    $contact_email = trim($_POST['contact_email'] ?? '');
    $contact_phone = trim($_POST['contact_phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $consultation_rate = trim($_POST['consultation_rate'] ?? '');
    $coverage_limit = trim($_POST['coverage_limit'] ?? '');
    $co_payment_percentage = trim($_POST['co_payment_percentage'] ?? '');
    $contract_start_date = trim($_POST['contract_start_date'] ?? '');
    $contract_end_date = trim($_POST['contract_end_date'] ?? '');
    $terms_conditions = trim($_POST['terms_conditions'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // Validation
    if (empty($provider_name)) {
        $errors[] = "Provider name is required";
    }
    
    if (empty($provider_code)) {
        $errors[] = "Provider code is required";
    } elseif (!preg_match('/^[A-Z0-9]{2,10}$/', $provider_code)) {
        $errors[] = "Provider code must be 2-10 uppercase letters or numbers";
    }
    
    if (!empty($contact_email) && !filter_var($contact_email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Please enter a valid email address";
    }
    
    if (!empty($contact_phone) && !preg_match('/^(\+254|0)[7-9]\d{8}$/', $contact_phone)) {
        $errors[] = "Please enter a valid Kenyan phone number";
    }
    
    if (!empty($co_payment_percentage) && ($co_payment_percentage < 0 || $co_payment_percentage > 100)) {
        $errors[] = "Co-payment percentage must be between 0 and 100";
    }
    
    if (!empty($consultation_rate) && $consultation_rate < 0) {
        $errors[] = "Consultation rate must be a positive number";
    }
    
    // Check for duplicate provider code
    if (empty($errors)) {
        $check_sql = "SELECT provider_id FROM insurance_providers WHERE provider_code = ?";
        $stmt = $conn->prepare($check_sql);
        $stmt->bind_param("s", $provider_code);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $errors[] = "An insurance provider with this code already exists";
        }
    }
    
    // If no errors, insert
    if (empty($errors)) {
        try {
            $conn->begin_transaction();
            
            $insert_sql = "INSERT INTO insurance_providers 
                          (provider_name, provider_code, contact_person, email, 
                           phone, address, consultation_rate, coverage_limit, 
                           co_payment_percentage, contract_start_date, contract_end_date, 
                           terms_conditions, is_active, created_at) 
                          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param("ssssssdddsssi", 
                $provider_name, $provider_code, $contact_person, $contact_email,
                $contact_phone, $address, $consultation_rate, $coverage_limit, 
                $co_payment_percentage, $contract_start_date, $contract_end_date, 
                $terms_conditions, $is_active
            );
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to add insurance provider");
            }
            
            $provider_id = $conn->insert_id();
            
            // Log activity
            $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, 
                           record_type, new_values, ip_address, logged_at) 
                           VALUES (?, 'CREATE', 'INSURANCE', ?, 'INSURANCE_PROVIDER', ?, ?, NOW())";
            
            $new_values = json_encode([
                'provider_name' => $provider_name,
                'provider_code' => $provider_code,
                'consultation_rate' => $consultation_rate
            ]);
            $ip_address = $_SERVER['REMOTE_ADDR'];
            
            $stmt = $conn->prepare($activity_sql);
            $stmt->bind_param("iiss", $user_id, $provider_id, $new_values, $ip_address);
            $stmt->execute();
            
            $conn->commit();
            
            $success_message = "Insurance provider added successfully!";
            $_POST = array();
            
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = "Failed to add provider: " . $e->getMessage();
        }
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Insurance Provider')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .form-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            border-radius: 12px 12px 0 0;
        }
        
        .form-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .form-body {
            padding: 1.5rem;
        }
        
        .form-label {
            font-weight: 500;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .required {
            color: #ef4444;
        }
        
        .form-control, .form-select {
            border: 1px solid #d1d5db;
            border-radius: 8px;
            padding: 0.75rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .import-banner {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .import-banner .btn {
            background: white;
            color: #667eea;
            border: none;
            font-weight: 600;
        }
        
        .import-banner .btn:hover {
            background: #f3f4f6;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <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">Add Insurance Provider</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_insurance_providers.php">Insurance Providers</a></li>
                                        <li class="breadcrumb-item active">Add Provider</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Bulk Import Banner -->
                    <div class="import-banner">
                        <div>
                            <i class="ri-file-excel-2-line fs-3 me-2"></i>
                            <span class="fs-5">Need to add multiple providers?</span>
                        </div>
                        <a href="import_insurance_providers.php" class="btn">
                            <i class="ri-upload-2-line me-1"></i> Bulk Import
                        </a>
                    </div>

                    <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>Error!</strong>
                        <ul class="mb-0 mt-2">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>Success!</strong> <?php echo htmlspecialchars($success_message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <form method="POST" id="providerForm">
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Provider Information</h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Provider Name <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="provider_name" 
                                               value="<?php echo htmlspecialchars($_POST['provider_name'] ?? ''); ?>" 
                                               placeholder="e.g., AAR Insurance Kenya" required>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Provider Code <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="provider_code" 
                                               value="<?php echo htmlspecialchars($_POST['provider_code'] ?? ''); ?>" 
                                               placeholder="e.g., AAR" 
                                               style="text-transform: uppercase;"
                                               pattern="[A-Z0-9]{2,10}" required>
                                        <small class="text-muted">2-10 uppercase letters/numbers</small>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Consultation Rate (KES)</label>
                                        <input type="number" class="form-control" name="consultation_rate" 
                                               value="<?php echo htmlspecialchars($_POST['consultation_rate'] ?? ''); ?>" 
                                               placeholder="e.g., 2500" min="0" step="0.01">
                                        <small class="text-muted">Agreed consultation charge</small>
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">Status</label>
                                        <div class="form-check form-switch mt-2">
                                            <input class="form-check-input" type="checkbox" name="is_active" 
                                                   id="isActive" <?php echo ($_POST['is_active'] ?? true) ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="isActive">Active</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Contact Information</h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Contact Person</label>
                                        <input type="text" class="form-control" name="contact_person" 
                                               value="<?php echo htmlspecialchars($_POST['contact_person'] ?? ''); ?>" 
                                               placeholder="Contact person name">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Contact Email</label>
                                        <input type="email" class="form-control" name="contact_email" 
                                               value="<?php echo htmlspecialchars($_POST['contact_email'] ?? ''); ?>" 
                                               placeholder="contact@provider.com">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Contact Phone</label>
                                        <input type="tel" class="form-control" name="contact_phone" 
                                               value="<?php echo htmlspecialchars($_POST['contact_phone'] ?? ''); ?>" 
                                               placeholder="0712345678">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label class="form-label">Physical Address</label>
                                        <textarea class="form-control" name="address" rows="2" 
                                                  placeholder="Enter physical address"><?php echo htmlspecialchars($_POST['address'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Coverage & Payment Terms</h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Coverage Limit (KES)</label>
                                        <input type="number" class="form-control" name="coverage_limit" 
                                               value="<?php echo htmlspecialchars($_POST['coverage_limit'] ?? ''); ?>" 
                                               placeholder="e.g., 1000000" min="0" step="1000">
                                        <small class="text-muted">Leave empty for unlimited coverage</small>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Co-Payment Percentage (%)</label>
                                        <input type="number" class="form-control" name="co_payment_percentage" 
                                               value="<?php echo htmlspecialchars($_POST['co_payment_percentage'] ?? ''); ?>" 
                                               placeholder="e.g., 10" min="0" max="100" step="0.01">
                                        <small class="text-muted">Patient's share of the cost</small>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Contract Details</h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Contract Start Date</label>
                                        <input type="date" class="form-control" name="contract_start_date" 
                                               value="<?php echo htmlspecialchars($_POST['contract_start_date'] ?? ''); ?>">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Contract End Date</label>
                                        <input type="date" class="form-control" name="contract_end_date" 
                                               value="<?php echo htmlspecialchars($_POST['contract_end_date'] ?? ''); ?>">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label class="form-label">Terms & Conditions</label>
                                        <textarea class="form-control" name="terms_conditions" rows="4" 
                                                  placeholder="Enter any special terms and conditions"><?php echo htmlspecialchars($_POST['terms_conditions'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="form-card">
                            <div class="form-body">
                                <div class="d-flex justify-content-between">
                                    <a href="list_insurance_providers.php" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line me-1"></i> Back to List
                                    </a>
                                    <div>
                                        <button type="reset" class="btn btn-secondary me-2">
                                            <i class="ri-refresh-line me-1"></i> Reset
                                        </button>
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i> Add Provider
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const providerCodeInput = document.querySelector('input[name="provider_code"]');
        providerCodeInput.addEventListener('input', function() {
            this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
        });
        
        const phoneInput = document.querySelector('input[name="contact_phone"]');
        phoneInput.addEventListener('input', function() {
            let value = this.value.replace(/\D/g, '');
            if (value.startsWith('254')) {
                value = '+' + value;
            } else if (value.length > 0 && !value.startsWith('0')) {
                value = '0' + value;
            }
            this.value = value;
        });
        
        document.getElementById('providerForm').addEventListener('submit', function(e) {
            const providerName = document.querySelector('input[name="provider_name"]').value.trim();
            const providerCode = document.querySelector('input[name="provider_code"]').value.trim();
            
            if (!providerName || !providerCode) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Required Fields',
                    text: 'Please fill in all required fields'
                });
                return false;
            }
            
            if (!/^[A-Z0-9]{2,10}$/.test(providerCode)) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Provider Code',
                    text: 'Provider code must be 2-10 uppercase letters or numbers'
                });
                return false;
            }
        });
    });
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>