<?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'] ?? '';
    $provider_id = $_POST['provider_id'] ?? '';
    $restriction_type = $_POST['restriction_type'] ?? '';
    $status = $_POST['status'] ?? 'ACTIVE';

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

    // Check if restriction already exists
    $sql = "SELECT restriction_id FROM scheme_provider_restrictions 
            WHERE corp_id = ? AND benefit_code = ? AND provider_id = ? AND status = 'ACTIVE'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('sii', $corp_id, $benefit_code, $provider_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $existing = $result->fetch_assoc();

    $conn->begin_transaction();

    try {
        if ($existing) {
            // Update existing restriction
            $sql = "UPDATE scheme_provider_restrictions SET 
                    restriction_type = ?,
                    status = ?,
                    modified_by = ?,
                    modified_at = NOW()
                    WHERE restriction_id = ?";

            $stmt = $conn->prepare($sql);
            $stmt->bind_param('ssii',
                $restriction_type,
                $status,
                $_SESSION['user_id'],
                $existing['restriction_id']
            );
        } else {
            // Insert new restriction
            $sql = "INSERT INTO scheme_provider_restrictions (
                    corp_id,
                    benefit_code,
                    provider_id,
                    restriction_type,
                    status,
                    created_by
                ) VALUES (?, ?, ?, ?, ?, ?)";

            $stmt = $conn->prepare($sql);
            $stmt->bind_param('siissi',
                $corp_id,
                $benefit_code,
                $provider_id,
                $restriction_type,
                $status,
                $_SESSION['user_id']
            );
        }

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

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

        $action = $existing ? 'UPDATE' : 'CREATE';
        $record_id = $existing ? $existing['restriction_id'] : $conn->insert_id;
        $new_values = json_encode([
            'corp_id' => $corp_id,
            'benefit_code' => $benefit_code,
            'provider_id' => $provider_id,
            'restriction_type' => $restriction_type,
            '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' => 'Provider restriction saved successfully'
        ]);

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

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

$conn->close();
?>