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

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

// Get corporate for dropdown
$sql = "SELECT corp_id, corporate FROM corporate WHERE cancelled = 0 ORDER BY corporate";
$result_corporate = $conn->query($sql);
$corporates = $result_corporate->fetch_all(MYSQLI_ASSOC);

// Get providers
$sql = "SELECT provider_id, provider_name FROM providers WHERE status = 1 ORDER BY provider_name";
$result_providers = $conn->query($sql);
$providers = $result_providers->fetch_all(MYSQLI_ASSOC);

// Get benefits
$sql = "SELECT code, benefit FROM benefit ORDER BY benefit";
$result_benefits = $conn->query($sql);
$benefits = $result_benefits->fetch_all(MYSQLI_ASSOC);

?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Scheme Policy Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</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' => 'Settings', 'title' => 'Scheme Policy Management')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <!-- Co-pay Settings -->
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Provider Co-pay Settings</h4>
                                </div>
                                
                                <div class="card-body">
                                    <form id="copayForm">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Corporate/Scheme</label>
                                                    <select class="form-select" name="corp_id" required>
                                                        <option value="">Select Corporate</option>
                                                        <?php foreach ($corporates as $corp): ?>
                                                            <option value="<?php echo $corp['corp_id']; ?>">
                                                                <?php echo htmlspecialchars($corp['corporate']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Benefit</label>
                                                    <select class="form-select" name="benefit_code" required>
                                                        <option value="">Select Benefit</option>
                                                        <?php foreach ($benefits as $benefit): ?>
                                                            <option value="<?php echo $benefit['code']; ?>">
                                                                <?php echo htmlspecialchars($benefit['benefit']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Co-pay Type</label>
                                                    <select class="form-select" name="copay_type" required>
                                                        <option value="PERCENTAGE">Percentage</option>
                                                        <option value="FIXED">Fixed Amount</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Co-pay Value</label>
                                                    <input type="number" class="form-control" name="copay_value" 
                                                           min="0" step="0.01" required>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Status</label>
                                                    <select class="form-select" name="status" required>
                                                        <option value="ACTIVE">Active</option>
                                                        <option value="INACTIVE">Inactive</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">&nbsp;</label>
                                                    <button type="submit" class="btn btn-primary w-100">
                                                        Save Co-pay Setting
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <!-- Provider Restriction -->
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Provider Restrictions</h4>
                                </div>
                                
                                <div class="card-body">
                                    <form id="restrictionForm">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Corporate/Scheme</label>
                                                    <select class="form-select" name="corp_id" required>
                                                        <option value="">Select Corporate</option>
                                                        <?php foreach ($corporates as $corp): ?>
                                                            <option value="<?php echo $corp['corp_id']; ?>">
                                                                <?php echo htmlspecialchars($corp['corporate']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Benefit</label>
                                                    <select class="form-select" name="benefit_code" required>
                                                        <option value="">Select Benefit</option>
                                                        <?php foreach ($benefits as $benefit): ?>
                                                            <option value="<?php echo $benefit['code']; ?>">
                                                                <?php echo htmlspecialchars($benefit['benefit']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Provider</label>
                                                    <select class="form-select" name="provider_id" required>
                                                        <option value="">Select Provider</option>
                                                        <?php foreach ($providers as $provider): ?>
                                                            <option value="<?php echo $provider['provider_id']; ?>">
                                                                <?php echo htmlspecialchars($provider['provider_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Restriction Type</label>
                                                    <select class="form-select" name="restriction_type" required>
                                                        <option value="ALLOWED">Allowed Only</option>
                                                        <option value="NOT_ALLOWED">Not Allowed</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">Status</label>
                                                    <select class="form-select" name="status" required>
                                                        <option value="ACTIVE">Active</option>
                                                        <option value="INACTIVE">Inactive</option>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label class="form-label">&nbsp;</label>
                                                    <button type="submit" class="btn btn-primary w-100">
                                                        Save Restriction
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>

                            <!-- Existing Settings -->
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Existing Policy Settings</h4>
                                </div>
                                
                                <div class="card-body">
                                    <ul class="nav nav-tabs" role="tablist">
                                        <li class="nav-item">
                                            <a class="nav-link active" data-bs-toggle="tab" href="#copayTab" role="tab">
                                                Co-pay Settings
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#restrictionsTab" role="tab">
                                                Provider Restrictions
                                            </a>
                                        </li>
                                    </ul>

                                    <div class="tab-content">
                                        <div class="tab-pane active" id="copayTab" role="tabpanel">
                                            <!-- Co-pay settings table -->
                                            <div class="table-responsive mt-4">
                                                <table class="table table-bordered">
                                                    <thead>
                                                        <tr>
                                                            <th>Corporate</th>
                                                            <th>Benefit</th>
                                                            <th>Type</th>
                                                            <th>Value</th>
                                                            <th>Status</th>
                                                            <th>Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="copayTableBody">
                                                        <!-- Data will be loaded here -->
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>

                                        <div class="tab-pane" id="restrictionsTab" role="tabpanel">
                                            <!-- Restrictions table -->
                                            <div class="table-responsive mt-4">
                                                <table class="table table-bordered">
                                                    <thead>
                                                        <tr>
                                                            <th>Corporate</th>
                                                            <th>Benefit</th>
                                                            <th>Provider</th>
                                                            <th>Type</th>
                                                            <th>Status</th>
                                                            <th>Actions</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody id="restrictionsTableBody">
                                                        <!-- Data will be loaded here -->
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                </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() {
    const copayForm = document.getElementById('copayForm');
    const restrictionForm = document.getElementById('restrictionForm');

    // Load existing settings
    loadCopaySettings();
    loadRestrictions();

    // Handle co-pay form submission
    copayForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        fetch('save_copay.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error || 'Failed to save co-pay setting');
            }

            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: data.message
            });

            this.reset();
            loadCopaySettings();
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: error.message
            });
        });
    });

    // Handle restriction form submission
    restrictionForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        fetch('save_restriction.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error || 'Failed to save provider restriction');
            }

            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: data.message
            });

            this.reset();
            loadRestrictions();
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: error.message
            });
        });
    });

    function loadCopaySettings() {
        fetch('get_copay_settings.php')
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    throw new Error(data.error || 'Failed to load co-pay settings');
                }

                const tbody = document.getElementById('copayTableBody');
                tbody.innerHTML = data.settings.map(setting => `
                    <tr>
                        <td>${setting.corporate}</td>
                        <td>${setting.benefit}</td>
                        <td>${setting.copay_type}</td>
                        <td>
                            ${setting.copay_type === 'PERCENTAGE' ? 
                              setting.copay_value + '%' : 
                              setting.copay_value.toLocaleString()}
                        </td>
                        <td>
                            <span class="badge bg-${setting.status === 'ACTIVE' ? 'success' : 'danger'}">
                                ${setting.status}
                            </span>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <button type="button" class="btn btn-info edit-copay"
                                        data-id="${setting.copay_id}">
                                    <i class="ri-edit-2-line"></i>
                                </button>
                                <button type="button" class="btn btn-danger delete-copay"
                                        data-id="${setting.copay_id}">
                                    <i class="ri-delete-bin-line"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                `).join('');

                // Add event listeners
                addCopayEventListeners();
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: error.message
                });
            });
    }

    function loadRestrictions() {
        fetch('get_restrictions.php')
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    throw new Error(data.error || 'Failed to load provider restrictions');
                }

                const tbody = document.getElementById('restrictionsTableBody');
                tbody.innerHTML = data.restrictions.map(restriction => `
                    <tr>
                        <td>${restriction.corporate}</td>
                        <td>${restriction.benefit}</td>
                        <td>${restriction.provider_name}</td>
                        <td>${restriction.restriction_type}</td>
                        <td>
                            <span class="badge bg-${restriction.status === 'ACTIVE' ? 'success' : 'danger'}">
                                ${restriction.status}
                            </span>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <button type="button" class="btn btn-info edit-restriction"
                                        data-id="${restriction.restriction_id}">
                                    <i class="ri-edit-2-line"></i>
                                </button>
                                <button type="button" class="btn btn-danger delete-restriction"
                                        data-id="${restriction.restriction_id}">
                                    <i class="ri-delete-bin-line"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                `).join('');

                // Add event listeners
                addRestrictionEventListeners();
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: error.message
                });
            });
    }

    function addCopayEventListeners() {
        document.querySelectorAll('.edit-copay').forEach(btn => {
            btn.addEventListener('click', () => editCopay(btn.dataset.id));
        });

        document.querySelectorAll('.delete-copay').forEach(btn => {
            btn.addEventListener('click', () => deleteCopay(btn.dataset.id));
        });
    }

    function addRestrictionEventListeners() {
        document.querySelectorAll('.edit-restriction').forEach(btn => {
            btn.addEventListener('click', () => editRestriction(btn.dataset.id));
        });

        document.querySelectorAll('.delete-restriction').forEach(btn => {
            btn.addEventListener('click', () => deleteRestriction(btn.dataset.id));
        });
    }
});
    </script>
</body>
</html>