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

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    exit;
}

try {
    $copay_id = $_GET['id'] ?? null;
    if (!$copay_id) {
        throw new Exception('Co-pay ID is required');
    }

    $sql = "SELECT sc.*, c.corporate, b.benefit
            FROM scheme_copay sc
            LEFT JOIN corporate c ON sc.corp_id = c.corp_id
            LEFT JOIN benefit b ON sc.benefit_code = b.code
            WHERE sc.copay_id = ?";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $copay_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $copay = $result->fetch_assoc();
    if (!$copay) {
        throw new Exception('Co-pay setting not found');
    }
    
    echo json_encode([
        'success' => true,
        'copay' => $copay
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>