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

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

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Not authorized']);
    exit;
}

try {
    // Get form data
    $corp_id = $_POST['corp_id'] ?? '';
    $benefit_code = $_POST['benefit_code'] ?? '';
    $copay_type = $_POST['copay_type'] ?? '';
    $copay_value = $_POST['copay_value'] ?? '';
    $status = $_POST['status'] ?? 'ACTIVE';

    // Validate required fields
    if (empty($corp_id) || empty($benefit_code) || empty($copay_type) || empty($copay_value)) {
        throw new Exception('All fields are required');
    }

    // Check if copay already exists for this corporate and benefit
    $sql = "SELECT copay_id FROM scheme_copay 
            WHERE corp_id = ? AND benefit_code = ? AND status = 'ACTIVE'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('si', $corp_id, $benefit_code);
    $stmt->execute();
    $result = $stmt->get_result();
    $existing = $result->fetch_assoc();

    $conn->begin_transaction();

    try {
        if ($existing) {
            // Update existing copay
            $sql = "UPDATE scheme_copay SET 
                    copay_type = ?,
                    copay_value = ?,
                    status = ?,
                    modified_by = ?,
                    modified_at = NOW()
                    WHERE copay_id = ?";

            $stmt = $conn->prepare($sql);
            $stmt->bind_param('sdsii',
                $copay_type,
                $copay_value,
                $status,
                $_SESSION['user_id'],
                $existing['copay_id']
            );
        } else {
            // Insert new copay
            $sql = "INSERT INTO scheme_copay (
                    corp_id,
                    benefit_code,
                    copay_type,
                    copay_value,
                    status,
                    created_by
                ) VALUES (?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            $stmt->bind_param('sisdsi',
                $corp_id,
                $benefit_code,
                $copay_type,
                $copay_value,
                $status,
                $_SESSION['user_id']
            );
        }

        if (!$stmt->execute()) {
            throw new Exception('Failed to save copay setting');
        }

        // Log activity
        $sql = "INSERT INTO activity_log (
                user_id,
                action,
                table_name,
                record_id,
                new_values,
                action_date
            ) VALUES (?, ?, 'scheme_copay', ?, ?, NOW())";

        $action = $existing ? 'UPDATE' : 'CREATE';
        $record_id = $existing ? $existing['copay_id'] : $conn->insert_id;
        $new_values = json_encode([
            'corp_id' => $corp_id,
            'benefit_code' => $benefit_code,
            'copay_type' => $copay_type,
            'copay_value' => $copay_value,
            'status' => $status
        ]);

        $stmt = $conn->prepare($sql);
        $stmt->bind_param('isss',
            $_SESSION['user_id'],
            $action,
            $record_id,
            $new_values
        );
        $stmt->execute();

        $conn->commit();

        echo json_encode([
            'success' => true,
            'message' => 'Copay setting saved successfully'
        ]);

    } catch (Exception $e) {
        $conn->rollback();
        throw $e;
    }

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

$conn->close();
?>