<?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();
}

// Get provider ID
$provider_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($provider_id <= 0) {
    header("Location: list_insurance_providers.php");
    exit();
}

// Fetch provider details
$query = "SELECT * FROM insurance_providers WHERE provider_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $provider_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header("Location: list_insurance_providers.php");
    exit();
}

$provider = $result->fetch_assoc();

// Handle 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']);
    $phone = trim($_POST['phone']);
    $email = trim($_POST['email']);
    $address = trim($_POST['address']);
    $consultation_rate = !empty($_POST['consultation_rate']) ? (int)$_POST['consultation_rate'] : null;
    $coverage_limit = !empty($_POST['coverage_limit']) ? (int)$_POST['coverage_limit'] : null;
    $coverage_percentage = (float)$_POST['coverage_percentage'];
    $copay_percentage = (float)$_POST['copay_percentage'];
    $claim_processing_days = (int)$_POST['claim_processing_days'];
    $smart_enabled = isset($_POST['smart_enabled']) ? 1 : 0;
    $smart_provider_key = trim($_POST['smart_provider_key']);
    $smart_medical_aid_code = trim($_POST['smart_medical_aid_code']);
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // Validate required fields
    if (empty($provider_name) || empty($provider_code)) {
        $error_message = "Provider name and code are required.";
    } else {
        // Check if provider code exists for other providers
        $check_query = "SELECT provider_id FROM insurance_providers WHERE provider_code = ? AND provider_id != ?";
        $check_stmt = $conn->prepare($check_query);
        $check_stmt->bind_param("si", $provider_code, $provider_id);
        $check_stmt->execute();
        
        if ($check_stmt->get_result()->num_rows > 0) {
            $error_message = "Provider code already exists.";
        } else {
            // Update provider
            $update_query = "UPDATE insurance_providers SET 
                            provider_name = ?,
                            provider_code = ?,
                            contact_person = ?,
                            phone = ?,
                            email = ?,
                            address = ?,
                            consultation_rate = ?,
                            coverage_limit = ?,
                            coverage_percentage = ?,
                            copay_percentage = ?,
                            claim_processing_days = ?,
                            smart_enabled = ?,
                            smart_provider_key = ?,
                            smart_medical_aid_code = ?,
                            is_active = ?
                            WHERE provider_id = ?";
            
            $update_stmt = $conn->prepare($update_query);
            $update_stmt->bind_param("ssssssiiddiissii",
                $provider_name, $provider_code, $contact_person, $phone, $email, $address,
                $consultation_rate, $coverage_limit, $coverage_percentage, $copay_percentage,
                $claim_processing_days, $smart_enabled, $smart_provider_key, 
                $smart_medical_aid_code, $is_active, $provider_id
            );
            
            if ($update_stmt->execute()) {
                $_SESSION['success_message'] = "Insurance provider updated successfully!";
                header("Location: view_insurance_provider.php?id=" . $provider_id);
                exit();
            } else {
                $error_message = "Error updating provider: " . $conn->error;
            }
        }
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit 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: 1.5rem;
            overflow: hidden;
        }
        
        .form-card-header {
            padding: 1.25rem 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
        }
        
        .form-card-header h5 {
            margin: 0;
            font-weight: 600;
            color: #1e293b;
            font-size: 1rem;
        }
        
        .form-card-body {
            padding: 1.5rem;
        }
        
        .form-label {
            font-weight: 500;
            color: #475569;
            font-size: 0.875rem;
            margin-bottom: 0.5rem;
        }
        
        .required::after {
            content: ' *';
            color: #ef4444;
        }
        
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.625rem 0.875rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .form-check-input:checked {
            background-color: #3b82f6;
            border-color: #3b82f6;
        }
        
        .btn-group-custom {
            display: flex;
            gap: 0.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">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <div class="d-flex align-items-center">
                                    <a href="view_insurance_provider.php?id=<?php echo $provider_id; ?>" class="btn btn-light btn-sm me-3">
                                        <i class="ri-arrow-left-line"></i> Back
                                    </a>
                                    <h4 class="mb-0">Edit Insurance Provider</h4>
                                </div>
                                <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">Providers</a></li>
                                        <li class="breadcrumb-item active">Edit Provider</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($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; ?>

                    <form method="POST" id="providerForm">
                        <div class="row">
                            <div class="col-lg-8">
                                <!-- Basic Information -->
                                <div class="form-card">
                                    <div class="form-card-header">
                                        <h5><i class="ri-information-line me-2"></i>Basic Information</h5>
                                    </div>
                                    <div class="form-card-body">
                                        <div class="row g-3">
                                            <div class="col-md-6">
                                                <label class="form-label required">Provider Name</label>
                                                <input type="text" class="form-control" name="provider_name" 
                                                       value="<?php echo htmlspecialchars($provider['provider_name']); ?>" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label required">Provider Code</label>
                                                <input type="text" class="form-control" name="provider_code" 
                                                       value="<?php echo htmlspecialchars($provider['provider_code']); ?>" required maxlength="20">
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Contact Information -->
                                <div class="form-card">
                                    <div class="form-card-header">
                                        <h5><i class="ri-contacts-line me-2"></i>Contact Information</h5>
                                    </div>
                                    <div class="form-card-body">
                                        <div class="row g-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Contact Person</label>
                                                <input type="text" class="form-control" name="contact_person" 
                                                       value="<?php echo htmlspecialchars($provider['contact_person']); ?>" maxlength="100">
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Phone</label>
                                                <input type="tel" class="form-control" name="phone" 
                                                       value="<?php echo htmlspecialchars($provider['phone']); ?>" maxlength="20">
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Email</label>
                                                <input type="email" class="form-control" name="email" 
                                                       value="<?php echo htmlspecialchars($provider['email']); ?>" maxlength="100">
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Address</label>
                                                <textarea class="form-control" name="address" rows="1"><?php echo htmlspecialchars($provider['address']); ?></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Coverage & Billing -->
                                <div class="form-card">
                                    <div class="form-card-header">
                                        <h5><i class="ri-money-dollar-circle-line me-2"></i>Coverage & Billing</h5>
                                    </div>
                                    <div class="form-card-body">
                                        <div class="row g-3">
                                            <div class="col-md-6">
                                                <label class="form-label">Consultation Rate (KES)</label>
                                                <input type="number" class="form-control" name="consultation_rate" 
                                                       value="<?php echo $provider['consultation_rate']; ?>" min="0" step="1">
                                            </div>
                                            <div class="col-md-6">
                                                <label class="form-label">Coverage Limit (KES)</label>
                                                <input type="number" class="form-control" name="coverage_limit" 
                                                       value="<?php echo $provider['coverage_limit']; ?>" min="0" step="1">
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label required">Coverage Percentage (%)</label>
                                                <input type="number" class="form-control" name="coverage_percentage" 
                                                       value="<?php echo $provider['coverage_percentage']; ?>" 
                                                       min="0" max="100" step="0.01" required>
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label required">Copay Percentage (%)</label>
                                                <input type="number" class="form-control" name="copay_percentage" 
                                                       value="<?php echo $provider['copay_percentage']; ?>" 
                                                       min="0" max="100" step="0.01" required>
                                            </div>
                                            <div class="col-md-4">
                                                <label class="form-label required">Claim Processing Days</label>
                                                <input type="number" class="form-control" name="claim_processing_days" 
                                                       value="<?php echo $provider['claim_processing_days']; ?>" 
                                                       min="1" required>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- SMART Integration -->
                                <div class="form-card">
                                    <div class="form-card-header">
                                        <h5><i class="ri-flashlight-line me-2"></i>SMART Integration</h5>
                                    </div>
                                    <div class="form-card-body">
                                        <div class="mb-3">
                                            <div class="form-check form-switch">
                                                <input class="form-check-input" type="checkbox" name="smart_enabled" 
                                                       id="smart_enabled" value="1" <?php echo $provider['smart_enabled'] ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="smart_enabled">
                                                    Enable SMART API Integration
                                                </label>
                                            </div>
                                        </div>
                                        
                                        <div id="smartFields" style="display: <?php echo $provider['smart_enabled'] ? 'block' : 'none'; ?>;">
                                            <div class="row g-3">
                                                <div class="col-md-6">
                                                    <label class="form-label">SMART Provider Key</label>
                                                    <input type="text" class="form-control" name="smart_provider_key" 
                                                           value="<?php echo htmlspecialchars($provider['smart_provider_key']); ?>" maxlength="50">
                                                </div>
                                                <div class="col-md-6">
                                                    <label class="form-label">SMART Medical Aid Code</label>
                                                    <input type="text" class="form-control" name="smart_medical_aid_code" 
                                                           value="<?php echo htmlspecialchars($provider['smart_medical_aid_code']); ?>" maxlength="50">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-4">
                                <!-- Status -->
                                <div class="form-card">
                                    <div class="form-card-header">
                                        <h5><i class="ri-settings-line me-2"></i>Status</h5>
                                    </div>
                                    <div class="form-card-body">
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" name="is_active" 
                                                   id="is_active" value="1" <?php echo $provider['is_active'] ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="is_active">
                                                Active Provider
                                            </label>
                                        </div>
                                        <p class="text-muted mt-2 mb-0" style="font-size: 0.75rem;">
                                            Inactive providers will not be available for patient registration
                                        </p>
                                    </div>
                                </div>

                                <!-- Actions -->
                                <div class="form-card">
                                    <div class="form-card-header">
                                        <h5><i class="ri-save-line me-2"></i>Actions</h5>
                                    </div>
                                    <div class="form-card-body">
                                        <div class="d-grid gap-2">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line me-1"></i> Update Provider
                                            </button>
                                            <a href="view_insurance_provider.php?id=<?php echo $provider_id; ?>" class="btn btn-secondary">
                                                <i class="ri-close-line me-1"></i> Cancel
                                            </a>
                                        </div>
                                    </div>
                                </div>

                                <!-- Info Card -->
                                <div class="form-card">
                                    <div class="form-card-header">
                                        <h5><i class="ri-information-line me-2"></i>Information</h5>
                                    </div>
                                    <div class="form-card-body">
                                        <p style="font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem;">
                                            <strong>Created:</strong> <?php echo date('M j, Y', strtotime($provider['created_at'])); ?>
                                        </p>
                                        <p style="font-size: 0.875rem; color: #64748b; margin: 0;">
                                            <strong>Provider ID:</strong> <?php echo $provider['provider_id']; ?>
                                        </p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    // Toggle SMART fields
    document.getElementById('smart_enabled').addEventListener('change', function() {
        document.getElementById('smartFields').style.display = this.checked ? 'block' : 'none';
    });

    // Form validation
    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: 'Validation Error',
                text: 'Provider name and code are required'
            });
            return false;
        }
    });
    </script>

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